您的位置:首页 > Web前端 > Node.js

Leetcode Remove Nth Node From End of List

2017-01-02 01:57 330 查看
题意:删除链表中倒数第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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表