Leetcode Remove Nth Node From End of List

来源:互联网 发布:网络黑白 花无涯 编辑:程序博客网 时间:2024/06/17 18:41

题意:删除链表中倒数第i个元素。

思路:用堆栈完成计数工作。

/** * 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) {        if(head == NULL) return head;        stack<ListNode*> mys;        ListNode* myhead = new ListNode(0);        ListNode* next = head;        myhead->next = next;        mys.push(myhead);        while(next) {            mys.push(next);            next = next->next;        }                ListNode* after = NULL;        next = mys.top();        mys.pop();        while(n --) {            after = next->next;            next = mys.top();            mys.pop();        }        next->next = after;                return myhead->next;    }};

另一种只遍历一边的做法是,在链表中标记第i个元素到结尾的长度。这样做目的是记录从头到达i-1个元素需要的循环次数。

/** * 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) {        ListNode* myhead = new ListNode(0);        myhead->next = head;        ListNode* mark = head;        ListNode* next = myhead;        while(n --) {            mark = mark->next;        }                while(mark) {//cout << "here" <<endl;            mark = mark->next;            next = next->next;        }        next->next = next->next->next;                return myhead->next;    }};


0 0
原创粉丝点击