LeetCode 19 Remove Nth Node From End of List(快慢指针)

题目链接:点击这里
在这里插入图片描述
题目给的链表不带空的头结点。为了方便对首结点进行操作,人为地设置一个空的头结点。

删除倒数第 n n 个节点,也就是删除从列表开头数起的第 ( l e n n + 1 ) (len−n+1) 个结点,其中 l e n len 是列表的长度。只要我们找到列表的长度 l e n len ,这个问题就很容易解决。

/**
 * 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 *kong = new ListNode(-1);  //设置一个空的头结点
        kong->next = head;

        ListNode *p = kong->next;
        int len = 0;    //获取链表长度
        while(p)
        {
            len++;
            p = p->next;
        }

        p = kong;
        int i = 1;
        while(i<len-n+1)
        {
            i++;
            p = p->next;
        }
        p->next = p->next->next;
        return kong->next;
    }
};

让快指针先走 n n 步,然后快慢指针开始同速前进。这样当快指针走到链表末尾 N U L L NULL 时,慢指针所在的位置就是倒数第 n n 个链表节点。

/**
 * 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 *kong = new ListNode(-1);  //设置一个空的头结点
        kong->next = head;

        ListNode *slow = kong, *fast = kong;
        
        for(int i = 1; i <= n + 1; i++)
            fast = fast->next;

        while(fast!=NULL)
        {
            slow = slow->next;
            fast = fast->next;
        }
        slow->next = slow->next->next;
        return kong->next;
    }
};
发布了708 篇原创文章 · 获赞 104 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/104100132