LeetCOde19. Remove Nth Node From End of List

来源:互联网 发布:辐射测试软件 编辑:程序博客网 时间:2024/05/06 05:10

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.

#include<cstdlib>#include<iostream>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {        int num=0,t=1,times=1;        ListNode *p=head;        while(p){            num++;            p=p->next;        }               if(n>num) return head;        if(n<=0)  return head;        if(n==num) {head=head->next; return head;}          p=head;        times = num-n;        while(t<times){            p=p->next;            ++t;        }        if(n==1){p->next=NULL;}        else{ p->next=(p->next)->next;}             return head;    }};void main(){    ListNode L1(1);    ListNode L2(2);    ListNode L3(3);    ListNode L4(4);    ListNode L5(5);    L1.next=&L2;    //L2.next=&L3;    //L3.next=&L4;    //L4.next=&L5;    ListNode *p;    p=&L1;    while(p->next){        cout<<(p->val)<<"->";        p=p->next;    }    cout<<(p->val)<<endl;    Solution So;    ListNode *res = So.removeNthFromEnd(&L1,1);    ListNode *p2=res;    while(p2->next){        cout<<(p2->val)<<"->";        p2=p2->next;    }    cout<<(p2->val)<<endl;}

这里写图片描述

0 0