原题
给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。
注意事项
链表中的节点个数大于等于n
样例
给出链表**1->2->3->4->5->null
和 n = 2.
删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.
**
解题思路
- 链表问题 - 快慢指针解决(Two Pointers)
- 块指针先走n步,然后快慢指针一起走,快指针走到尾,慢指针距离尾部差n个节点
- 删除节点
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