19. Remove Nth Node From End of List 刪除倒數第n各節點
阿新 • • 發佈:2017-11-11
得到 listnode 負責 style pre def 正數 always ast
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.
刪除倒數第n個節點,主要有兩種做法
法一:先遍歷得到鏈表的長度length,倒數第n個就是正數第length-n+1個(如1 2 3,倒數第三個節點就是3-3+1=1,即第一個節點)
/** * 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, intn) { ListNode* newlist= new ListNode(0); newlist->next = head; //帶頭節點的鏈表 int length = 0; ListNode* first = head; while(first != NULL){ //得到鏈表長度 length++; first = first->next; } if(n > length) return NULL;int n1 = length + 1 - n;//倒數第n個是在正數第n1個節點 first = newlist; while(n1 - 1 > 0){ //找到目標節點的前一個位置,便於刪除目標節點 n1--; first = first->next; } first->next = first->next->next; //刪除目標節點 return newlist->next; //返回不帶頭節點的鏈表 } };
法二:利用兩個指針,快指針先走,找到第n個節點,再啟動慢指針。
此時快慢指針相距n,讓兩個指針一起走,快指針走到尾節點時,慢指針剛好到倒數第n個節點。
/** * 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) return nullptr; ListNode new_head(-1); new_head.next = head; ListNode *slow = &new_head, *fast = &new_head; for (int i = 0; i < n; i++) //快指針先走到第n個節點 fast = fast->next; while (fast->next) //快慢指針一起走 { fast = fast->next; slow = slow->next; } ListNode *to_do_deleted = slow->next; //這兩行負責刪除操作 slow->next = slow->next->next; delete to_do_deleted; return new_head.next; } };
19. Remove Nth Node From End of List 刪除倒數第n各節點