Remove Nth Node From End of List

问题描述:

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.

方法一:直观想法,即将指针移动 L-n 下
1.将链表遍历一遍,计算出L,再计算L-n,得到该点
2.设定一个计数值size,当size<=n时候,指针不移动,大于n时,指针移动,则刚好移动到L-n
代码如下:

def removeNthFromEnd(self, head, n):
    size = 1
    cur = p = head
    while cur.next:
        size += 1
        cur = cur.next
        if size > n + 1:
            p = p.next
    if size == n:
        return head.next
    else:
        p.next = p.next.next
        return head

方法二:解答(为了降低遍历的次数,采取两个指针,时间复杂度降低为O(L) ):

  1. 设置两个指针p1,p2,两个指针的间隔为n
  2. 当p2指向链表的尾部的时候,p1指向n+1的位置
  3. 通过p1.next = p1.next.next的方式去掉第n个元素
  4. 特殊情况:当n=链表长度,返回空表

代码如下:

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        p1 = p2 = head

        while n:
            p2 = p2.next
            n = n - 1
            if p2 is None:
                return head.next

        while p2.next is not None:
            p1 = p1.next
            p2 = p2.next

        p1.next = p1.next.next

        return head

若把上述特殊情况一般化,则给链表增加一个头部first,代码如下

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        first = ListNode(0)
        first.next = head
        p1 = p2 = first

        while n:
            p2 = p2.next
            n = n - 1

        while p2.next is not None:
            p1 = p1.next
            p2 = p2.next

        p1.next = p1.next.next

        return first.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值