1. 程式人生 > >【LeetCode & 劍指offer刷題】連結串列題4:22 刪除連結串列中倒數第k個結點(19. Remove Nth Node From End of List)

【LeetCode & 劍指offer刷題】連結串列題4:22 刪除連結串列中倒數第k個結點(19. Remove Nth Node From End of List)

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

19. Remove Nth Node From End of List

Given a linked list, remove the   n -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?   /**  * Definition for singly-linked list.  * struct ListNode {  *     int val;
 *     ListNode *next;  *     ListNode(int x) : val(x), next(NULL) {}  * };  */ /*方法:雙指標法,前面的指標比後面的領先n+1步,往前走,直到前面的指標到達末尾結點,所要資訊,可以從落後的指標獲取 如果只是查詢倒數第n個結點,可以只用領先n步即可   fast領先n+1步,
fast到nullptr,slow到達倒數n+1位置 刪除倒數n位置結點即可 (prehead的使用) */ class Solution { public :     ListNode * removeNthFromEnd ( ListNode * head , int n )     {         //防禦性程式設計         if ( head == nullptr || n == 0 ) return head ;                 ListNode prehead ( 0 ); //建立頭結點,方便處理只有一個結點或者移除首結點的特殊情況         prehead . next = head ; //指向首結點         ListNode * fast = & prehead , * slow = & prehead ;                 //fast領先n+1步,迴圈退出時,fast在位置n+1,slow在位置0(prehead位置為0)         for ( int i = 1 ; i <= n + 1 ; i ++)         {             fast = fast -> next ;         //    if(fast == nullptr) return nullptr; //對於查詢,需要處理如果n小於連結串列長度的情況         }                 //同時移動fast和slow         while ( fast != nullptr )         {             fast = fast -> next ;             slow = slow -> next ;         } //結果為fast指向最後一個結點之後為nullptr,slow指向倒數第(n+1)個結點 (找到倒數第n+1個結點,方便刪除下一個結點)                 ListNode * temp = slow -> next ; //倒數第n個結點         slow -> next = slow -> next -> next ; //跳過倒數第n個結點         delete temp ; //刪除倒數第n個結點                 return prehead.next;             } }; /* 方法二 class Solution { public:     ListNode* removeNthFromEnd(ListNode* head, int n)     {         if(head == NULL || n <= 0)             return head;         if(head->next == NULL)             return NULL;                 ListNode *p1 = head, *p2 = head;         while(n > 0)         {             p1 = p1->next;             n --;         }         if(p1 == NULL) // 要刪除的為head節點         {                     head = head->next;             delete p2;             return head;         }                 ListNode *pre = head;         while(p1 != NULL)         {             pre = p2;             p1 = p1->next;             p2 = p2->next;         }         pre->next = p2->next;         delete p2;         return head;     } }; */