標籤:style blog http color strong os
題目: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.
Note:
Given n will always be valid.
Try to do this in one pass.
個人思路:
1、設定兩個指標,一個快,一個慢,根據給定的n,讓快指標先走n步,之後再同時走,直到快指標走到末節點,此時慢指標走到要刪除節點的父節點
2、注意一下邊界條件即可,鏈表為空白、刪除前端節點等情況
代碼:
1 #include <stddef.h> 2 3 struct ListNode 4 { 5 int val; 6 ListNode *next; 7 ListNode(int x) : val(x), next(NULL) {}; 8 }; 9 10 class Solution11 {12 public:13 ListNode* removeNthFromEnd(ListNode *head, int n)14 {15 if (!head)16 {17 return NULL;18 }19 20 ListNode *slow = head;21 ListNode *fast = head;22 23 //快指標先走n步24 for (int i = 0; i < n; ++i)25 {26 fast = fast->next;27 }28 //快指標為空白,表明要刪除的節點為前端節點29 if (!fast)30 {31 head = head->next;32 delete slow;33 slow = NULL;34 35 return head;36 }37 //快指標走到最後一個節點時,慢指標走到要刪除節點的前一個節點38 while (fast->next)39 {40 slow = slow->next;41 fast = fast->next;42 }43 //刪除節點44 ListNode *deleted = slow->next;45 slow->next = deleted->next;46 delete deleted;47 deleted = NULL;48 49 return head;50 }51 };52 53 int main()54 {55 return 0;56 }View Code
網上的文章大部分都是這個思路