思路
本题关键在于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