LeetCode19 Remove Nth Node From End of List

题意:

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处理返回问题。

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* removeNthFromEnd(ListNode* head, int n) {
12         ListNode dummy(0);
13         dummy.next = head;
14         head = &dummy;
15         ListNode* chaser = head;
16         ListNode* runner = head;
17         for (int i = 0; i < n; ++i) {
18             runner = runner -> next;
19         }
20         while (runner -> next != nullptr) {
21             runner = runner -> next;
22             chaser = chaser -> next;
23         }
24         ListNode* temp = chaser -> next;
25         chaser -> next = chaser -> next -> next;
26         delete temp;
27         return dummy.next;
28     }
29 };

 

posted @ 2016-08-05 22:20  wangxiaobao1114  阅读(499)  评论(0编辑  收藏  举报