- 轉載請註明作者和出處:http://blog.csdn.net/u011475210
- 代碼地址:https://github.com/WordZzzz/Note/tree/master/LeetCode
- 刷題平臺:https://www.nowcoder.com/ta/leetcode
- 題 庫:Leetcode經典編程題
- 編 者:WordZzzz
題目描述
Given a linked list, remove the n th 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.
解題思路
刪除倒數第n個結點,我們就需要找到倒數第n個結點。於是,我們可以利用快慢指針來實現。
首先,fast走n步指向第n個結點;接着,fast和slow一起走,直到fast指向尾結點;最後,刪除元素(這裏需要注意的是加入pre來判斷刪除元素是否爲頭結點)。
C++版代碼實現
/**
* 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 NULL;
ListNode *slow = head;
ListNode *fast = head;
ListNode *pre = NULL;
//fast先走n步,到達第n個結點
while(--n)
fast = fast->next;
//fast和slow一起走,直到fast走到鏈表尾部
while(fast->next != NULL){
pre = slow;
slow = slow->next;
fast = fast->next;
}
//此處用於判斷刪除的結點是否爲頭結點
if(pre != NULL)
pre->next = slow->next;
else
head = head->next;
return head;
}
};
系列教程持續發佈中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~
完的汪(∪。∪)。。。zzz