Remove Nth Node From End of List

来源:互联网 发布:油蜡皮沙发价格知乎 编辑:程序博客网 时间:2024/04/26 10:23
/** * 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) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if (!head) return NULL;        ListNode *cur=head, *pre=NULL;        int len=0;        while (cur) {            len++;            cur = cur->next;        }        if (len<n || n==0) {            return head;        }        int i=0;        ListNode *res = new ListNode(0);        res->next = head;        pre = res;        cur=pre->next;         while(i<len-n){            pre=cur;            cur=cur->next;            i++;        }        pre->next = cur->next;        return res->next;    }};

原创粉丝点击