边工作边刷题:70天一遍leetcode: day 38-2
Remove Nth Node From End of List
要点
- first和second指针的距离:n是从1开始计数的,所以second指向的node和被删的node之间共n个node(包括这两个边界node)。first指向被删node的前一个,这样才能进行list node的删除
- 根据上面的距离关系,first开始指向dummy,second要首先从head开始单独移动n-1步,之后移动second到最后一个node,这样first.next指向被删node。所以用second.next!=null作为循环条件
# 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
"""
dummy = ListNode(0)
dummy.next = head
first, second = dummy, head
while second.next and n>1:
second=second.next
n-=1
if n!=1:
return None
while second.next:
first=first.next
second=second.next
first.next=first.next.next
return dummy.next