LeetCode刷題筆記(鏈表):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.

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個結點,我們就需要找到倒數第n個結點。於是,我們可以利用快慢指針來實現。

首先,fast走n步指向第n個結點;接着,fast和slow一起走,直到fast指向尾結點;最後,刪除元素(這裏需要注意的是加入pre來判斷刪除元素是否爲頭結點)。

C++版代碼實現

/**
 * 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 == NULL)
            return NULL;

        ListNode *slow = head;
        ListNode *fast = head;
        ListNode *pre = NULL;
        //fast先走n步,到達第n個結點
        while(--n)
            fast = fast->next;
        //fast和slow一起走,直到fast走到鏈表尾部
        while(fast->next != NULL){
            pre = slow;
            slow = slow->next;
            fast = fast->next;
        }
        //此處用於判斷刪除的結點是否爲頭結點
        if(pre != NULL)
            pre->next = slow->next;
        else
            head = head->next;

        return head;
    }
};

系列教程持續發佈中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

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