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

556 篇文章 2 订阅
441 篇文章 0 订阅

Description

Given a linked list, remove the n-th node from the end of list and return its head.

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.

Follow up:

Could you do this in one pass?

分析

题目的意思是:移除链表中倒数第k个节点。

  • 这道题利用快慢指针,首先快指针先移动k个节点,然后快慢指针一起移动,当块指针移动到末尾时,慢指针指向的节点的下一个节点就是要移除的节点。
  • 这里利用了一个trick,就是在表头多加了一个节点,这样能避免头节点为空的情况,也能够在最后返回链表的头节点。

C++代码

/**
 * 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* pre=new ListNode(-1);
        pre->next=head;
        ListNode* fast=pre;
        while(n>0&&fast){
            fast=fast->next;
            n--;
        }
        if(n>0){
            return NULL;
        }
        ListNode* slow=pre;
        while(fast->next){
            slow=slow->next;
            fast=fast->next;
        }
        slow->next=slow->next->next;
        return pre->next;
    }
};

Python 代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        root_node=ListNode()
        root_node.next=head
        for i in range(n):
            head=head.next
        p=root_node.next
        pre=root_node
        while head:
            pre=pre.next
            p=p.next
            head=head.next
        pre.next=p.next
        return root_node.next

第二个版本:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        # two pointers
        dummpy = ListNode(-1)
        dummpy.next = head
        p = dummpy
        for i in range(n):
            p = p.next
        pre = dummpy
        while p and p.next:
            p = p.next
            pre = pre.next
        pre.next = pre.next.next
        return dummpy.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值