原題
給定一個鏈表,刪除鏈表中倒數(shù)第n個節(jié)點,返回鏈表的頭節(jié)點。
注意事項
鏈表中的節(jié)點個數(shù)大于等于n
樣例
給出鏈表**1->2->3->4->5->null
和 n = 2.
刪除倒數(shù)第二個節(jié)點之后,這個鏈表將變成1->2->3->5->null.
**
解題思路
- 鏈表問題 - 快慢指針解決(Two Pointers)
- 塊指針先走n步,然后快慢指針一起走,快指針走到尾,慢指針距離尾部差n個節(jié)點
- 刪除節(jié)點
node.next = node.next.next
完整代碼
# 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
"""
slow, fast = head, head
for i in range(n):
fast = fast.next
if not fast:
head = slow.next
else:
while fast.next != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head