【LeetCode】19. Remove Nth Node From End of List(C++)
阿新 • • 發佈:2018-12-02
地址:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
題目:
Given a linked list, remove the -th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
理解:
最開始想到了快慢指標。。然而發現好像實現不了。
那就用最簡單的兩次遍歷實現吧。
實現:
由於leetcode的連結串列都不帶頭節點,因此需要判斷一下。或者簡單粗暴的方式是加一個頭節點。
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* p=head; int cnt=0; while(p){ ++cnt; p=p->next; } if(n==cnt) return head->next; else{ int times=cnt-n-1; p=head; while(times){ p=p->next; --times; } p->next=p->next->next; return head; } } };
一次遍歷的實現
應該在某個地方看過這個方法?記不清了,還是看了一眼solution。。用兩個指標,不過這裡的快慢指標的移動速度是相同的。只是快指標比慢指標一開始多移動n+1次,這樣最後快指標到n+1時,慢指標就到了null。為了方便刪除節點,在開頭加一個頭節點。
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* nHead = new ListNode(0); nHead->next = head; ListNode *slow = nHead, *fast = nHead; ++n; while (n) { fast = fast->next; --n; } while (fast) { slow = slow->next; fast = fast->next; } slow->next = slow->next->next; head= nHead->next; return nHead->next; } };