leetcode 19 removeNthFromEnd

来源:互联网 发布:数据集成工具 编辑:程序博客网 时间:2024/06/06 09:14

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.

/** * 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) {        vector<ListNode*> v;        // gurantee the size is bigger than one;        if (head->next == NULL) return NULL;        ListNode* p = head;        size_t id = 0;        while (p -> next != NULL) {            v.push_back(p);            p = p->next;        }        // the last one;        v.push_back(p);        p = NULL;        vector<ListNode*>::size_type size = v.size();        if (size - n == 0) {    // delete the head             p = head;            head = head->next;            free(p);        } else { // will visit the struct before the one that will be deleted           // assert(size - n - 1 >= 0);            p = v[size - n - 1];            ListNode* pdel = p-> next;            p->next = pdel->next;            free(pdel);           // pdel = NULL;           // p = NULL;         }        return head;    }}; // runtime distribution 54.48%

参考后

/** * 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) {        // The "dummy" node is used to simplify some corner cases such as a         // list with only one node, or removing the head of the list.         ListNode *dummy = new ListNode(0);        dummy -> next = head;        ListNode *first = dummy;        ListNode *second = dummy;        // first pointer go first        for (int i = 0; i < (n + 1); ++i) first = first->next;        while (first != NULL) {            first = first->next;            second = second->next;        }        ListNode* pdel = second->next;        second->next = pdel->next;        free(pdel);        return dummy->next;        }}; // runtime distribution: 14.50%    // i don't konw why