[LeetCode]Remove N-th node from end of list

来源:互联网 发布:流星网络电视vip破解版 编辑:程序博客网 时间:2024/05/18 20:09

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.

class Solution {public:    ListNode *removeNthFromEnd(ListNode *head, int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(head==NULL)            return NULL;                    ListNode *n1=head;        ListNode *n2=head;        ListNode *tmp;                for(int i=0;i<n;i++)        {            if(n2==NULL) //size of lists < n                return head;            n2=n2->next;        }                if(n2==NULL)        {            //remove header            tmp=head;            head=n1->next;            delete tmp;            return head;        }                while(n2->next!=NULL)        {            n1=n1->next;            n2=n2->next;        }                //remove n1->next;        tmp=n1->next;        n1->next=n1->next->next;        delete tmp;                return head;    }};