Remove Nth Node From End of List

来源:互联网 发布:python安装socket库 编辑:程序博客网 时间:2024/04/30 13:01
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *removeNthFromEnd(ListNode *head, int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        ListNode *pre = new ListNode(0);        pre->next=head;        ListNode *p1=pre,*p2=pre,*ret=NULL;        while(n--)p2=p2->next;        while(p2->next!=NULL){            p1=p1->next;            p2=p2->next;        }        p1->next=p1->next->next;        return pre->next;    }};