Remove Nth Node From End
题目描述
Given a linked list, remove the nth node from the end of list and return its head.
For 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. Try to do this in one pass.
解题方法
遇到linked list的问题首先问自己
- head确定能保留吗?那么需要dummy node吗?
这一题head也不一定能够保留,所以要用dummy node来做,两个快慢指针的做法,快指针先跑出去n步
我们要删去 nth node from end, nth node到tail的距离是n-1, 而我们要获得是Nth node前面一个, 那么它跟tail的距离是n, 所以快指针应该先走出n步。
Solution
# 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
"""
if not head:
return
dummy = ListNode(0) # dummy node
dummy.next = head
p1 = dummy
p2 = dummy
for i in range(n):
p2 = p2.next
while p2 and p2.next:
p1 = p1.next
p2 = p2.next
p1.next = p1.next.next
return dummy.next