標簽: C++ 算法 LeetCode 鏈表
每日算法——leetcode系列
問題 Remove Nth Node From End of List
Difficulty: Easy
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.
Note:
Given n will always be valid.
Try to do this in one pass.
/**
* 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) {
}
};
翻譯
從鏈表末尾刪除第n個節(jié)點
難度系數(shù):簡單
給定一個鏈表砍艾,從鏈表末尾刪除第n個節(jié)點并返回鏈表
例如:
給定鏈表: 1->2->3->4->5, and n = 2梦皮。
從尾部刪除第二個節(jié)點后剑肯,此鏈表變?yōu)?1->2->3->5。
注意:
- 給定的n總是有效的
- 試著一次遍歷解決問題
思路
此題關鍵點在于找到從尾部數(shù)的第n個節(jié)點竞滓,由于是單向鏈表撇吞,并且題目要求是一次遍歷,肯定有一個取巧的辦法。
定理:最后一個節(jié)點到從尾部數(shù)的第n個節(jié)點相差為n(廢話步氏!)
維護雙指針胖喳,讓第一個指針先走n步,這時候第二個指針和第一個指針相差n步较剃,再同時移動兩個指針确垫,這樣這兩個指針一直相差n步删掀,當?shù)谝粋€節(jié)點指向尾部是控硼,第二個節(jié)點就是要打的從尾部數(shù)第n個節(jié)點
代碼
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if (head == nullptr || n <= 0) {
return nullptr;
}
ListNode tempHead(-1);
tempHead.next = head;
head = &tempHead;
ListNode *p1 = head, *p2 = head;
for (int i = 0; i < n; ++i) {
if (p1 == nullptr){
return nullptr;
}
p1 = p1->next;
}
while (p1->next != nullptr) {
p1 = p1->next;
p2 = p2->next;
}
p2->next = p2->next->next;
return head->next;
}
};