Leetcode - 19. 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.

解法一

/**
 * 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) {
        int length = 0;
        ListNode* hd = head;
        ListNode* newHead = head;

        // 考慮1個元素 eg:[1] 1
        if(head->next==NULL)return NULL;

        while(head){
            head = head->next;
            length++;
        }
        // 考慮除去第一個元素
        if(n==length)
        {
            hd=hd->next;
            return hd;
        }
        // 考慮去除中間元素
        n = length-n;
        for(int i=0;i<n-1;i++){
            hd = hd->next;
        }

       hd->next = hd->next->next;       
        return newHead;
    }
};

解法二

  • 引入newHead(-1)是爲了保證在刪除首元素時避免循環的first->next不存在。eg: N爲原鏈表長度時,first遍歷後first == NULL
  • 由於開頭加了一個元素,first指針在遍歷N步後
  • 引入second指針隨着first的遍歷完全,指向被刪除元素的前一個位置。
  • 最後,second->next = second->next->next;
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* newHead = new ListNode(-1);
        newHead->next = head;

        ListNode*first = newHead;
        ListNode*second = newHead;

        for(int i=0;i<n;i++){
            first = first->next;
        }

        while(first->next){
            first = first->next;
            second = second->next;
        }

        ListNode* tmp = second->next;
        second->next = second->next->next;
        delete tmp;

        return newHead->next;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章