leetcode: remove-nth-node-from-end-of-list:刪除倒數第n個節點

題目描述:

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都是有效的。

思路:這道題和rotate-list的題非常像。https://blog.csdn.net/Qiana_/article/details/81488907

不過rotate這道題的k有可能是超過鏈表長度的值,所以需要先遍歷一遍鏈表,記錄鏈表的長度。這道題給的n都是有效的,可以採用快慢指針的方法,讓快指針先走n步,然後快慢指針再一起走,當快指針走到鏈表尾的時候,慢指針走到待刪除節點的前一個節點。然後慢指針指向待刪除節點的後一個節點,刪除待刪除節點即可。

AC代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    //O(n)
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        if(head == NULL)
            return head;
        ListNode* newHead = new ListNode(0);
        newHead->next = head;
        head = newHead;
        ListNode* fast = head;
        ListNode* slow = head;
        //fast先走n步
        for(int i = 0;i < n;i++)
            fast = fast->next;
        while(fast->next)
        {
            fast = fast->next;
            slow = slow->next;
        }
        //此時slow在待刪除節點的前一個位置
        ListNode* del = slow->next;
        slow->next = del->next;
        delete del;
        return newHead->next;
    }
};

(*^▽^*)

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