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

LeetCode19 Remove Nth Node From End of List

2016-08-05 22:20 330 查看
题意:

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.

Try to do this in one pass. (Easy)

分析:题目虽然是easy,但是用one pass做起来还是包含几个链表常用的手法的,有参考价值;

链表算法上没有什么难的,就是代码上仔细,再熟悉几种处理方法即可。

1.Two pointers。 利用快慢指针,快指针先走n步,然后一起走,快的下一步到终点了,慢的到达要删除的前一位;

2. dummy node。 凡是head位置可能被删掉,返回出现问题,用dummy node处理返回问题。

代码:

/**
* 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 dummy(0);
dummy.next = head;
head = &dummy;
ListNode* chaser = head;
ListNode* runner = head;
for (int i = 0; i < n; ++i) {
runner = runner -> next;
}
while (runner -> next != nullptr) {
runner = runner -> next;
chaser = chaser -> next;
}
ListNode* temp = chaser -> next;
chaser -> next = chaser -> next -> next;
delete temp;
return dummy.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: