1. 程式人生 > >LeetCode---Remove Nth Node From End of List

LeetCode---Remove Nth Node From End of List

Question: Remove Nth Node From End of List

Description: 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: n will always be valid.

 

Solution Code:

class Solution {
    /**
     * 注意以下幾點:
     * (1)提示: n will always be valid. 所以不需要考慮n<=0 或者超過連結串列長度的問題
     * (2)若待刪除節點不是頭結點,則不需要維護頭結點
     * (3)待刪除節點是頭結點的情況,需要注意
     */
public:
    ListNode* removeNthFromEnd(ListNode* head, int
n) { if (head == NULL) return NULL; ListNode* pRight = head; ListNode* pLeft = head; ListNode* pHead = head; int count = 0; while(pRight != NULL && count < n){ pRight = pRight->next; ++count; }
// 待刪除節點是頭結點的情況 if(pRight == NULL){ pHead = head->next; free(head); return pHead; } // 查詢待刪除節點的前一個節點 while(pRight->next != NULL){ pRight = pRight->next; pLeft = pLeft->next; } // 執行刪除 ListNode* pDelete = pLeft->next; pLeft->next = pLeft->next->next; free(pDelete); return pHead; } };

Reports: Runtime: 4 ms, faster than 100.00% of C++ online submissions for Remove Nth Node From End of List.