LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List (Medium) 《剑指offer》第二十二题:链表中倒数第k个结点

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

来源:力扣(LeetCode)

解法一:快慢指针,一次遍历。

/**
 * 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) {
        
        ListNode* pFast = head;
        ListNode* pSlow = head;

        for (int i = 0; i < n; ++i)  //快指针先走n步
            pFast = pFast->next;

        if (pFast == nullptr) return head->next;  //删除头节点

        while (pFast->next != nullptr)  //快指针走到链表尾, 慢指针则为倒数n-1
        {
            pFast = pFast->next;
            pSlow = pSlow->next;
        }

        //跳过待删除节点
        pSlow->next = pSlow->next->next;

        return head;
    }
};

解法二:两次遍历。

/**
 * 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* pNode = head;

        for (; pNode != nullptr; pNode = pNode->next)  //计算链表长度
            ++length;

        if (length == n) return head->next;  //删除头节点

        pNode = head;
        for (int i = 0; i < (length - n - 1); ++i)  //找到待删除的节点的前一节点
            pNode = pNode->next;
            
        if (pNode->next)
            pNode->next = pNode->next->next;  //跳过此节点

        return head;
    }
};

类似题目:《剑指offer》第二十二题:链表中倒数第k个结点

猜你喜欢

转载自www.cnblogs.com/ZSY-blog/p/12811655.html
今日推荐