leetcode#19 Remove Nth Node From End of List

Posted 老鼠阿尔吉侬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode#19 Remove Nth Node From End of List相关的知识,希望对你有一定的参考价值。

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

示例:

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

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

说明:

给定的 n 保证是有效的。

进阶:

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

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    //如果要遍历一次,必须快慢指针,而n始终有效,我们可以大胆地遍历
    //要删除倒数第n个指针,我们要遍历到倒数第n-1个指针
    //一个遍历了length 一个遍历了length-n
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        auto h=head;
        while(n>0)//让h前进n个结点
        {
            h=h->next;
            n--;
        }
        if(!h) return head->next;//h到了尾部,恰好是要删除的结点
        auto slow=head;//然后让slow和h一起移动,这样slow的next就是待删除结点,h的next是null
        while(h&&h->next)//移动n次之后,自己可能在tail,或者下一个是tail
        {
            h=h->next;
            slow=slow->next;
        }
        auto temp=slow->next->next;//我们没有删除那个结点,因为我们不在乎内存泄露
        slow->next=temp;
        return head;

    }
};

 

以上是关于leetcode#19 Remove Nth Node From End of List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode19. Remove Nth Node From End of List

leetcode 19. Remove Nth Node From End of List

LeetCode 19. Remove Nth Node From End of List

[LeetCode] 19. Remove Nth Node From End of List

Leetcode 19. Remove Nth Node From End of List(python)

LeetCode(19) - Remove Nth Node From End of List