LeetCode(2)——链表——删除倒数第n个节点

  1. 删除链表的倒数第 N 个结点

题目大意:
如题意,删除倒数第n个节点,并返回头指针。

思路:
典型的双指针题。同样,可能会删除头指针,所以为了同一操作,虚拟头节点是更好的选择^ - ^。

题解:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head == nullptr || head->next == nullptr)
            return nullptr;

        ListNode* newhead = new ListNode();
        newhead->next = head;


        ListNode* fast = newhead, *slow = newhead;

        for(int i = 0; i < n; ++i)
            fast = fast->next;
        
        while(fast->next != nullptr)
        {
            fast = fast->next;
            slow = slow->next;
        }

        ListNode* temp = slow->next->next;
        slow->next = temp;

        return newhead->next;
    }
};

你可能感兴趣的:(面试,#,LeetCode,链表,leetcode)