19. Remove Nth Node From End of List

思路

本题关键在于do this in one pass,否则可以直接第一遍遍历求List的长度,再求n-th node from the start of list。

首先假设List的长度是N,则移动N次后ListNode为none,以题中示例为例,n=2,N=5时,ListNode移动两次之后,还有三次ListNode为none,而我们需要去掉的数恰好就是从头开始移动三位之后的数。

为缩短一次移动我们用head.next是否为空进行判断:

        while(head.next):
            head = head.next
            head1 = head1.next

但又会出现问题,比如这一点输入:

[1,2,3,4,5]
5

当head是None时,head.next会报错,对这种情况我们单独处理

        if head == None:
            return head1.next

AC代码

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

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        head1 = head
        head2 = head
        for _ in range(n):
            head = head.next
        if head == None:
            return head1.next
        while(head.next):
            head = head.next
            head1 = head1.next
        head1.next = head1.next.next
        return head2
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值