题目
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
方法:双指针法
- 设置虚头节点,方便删除头节点
- 若要寻找倒数第 n 个节点,那么可以使得 fast 指针比 slow 指针先走 n 步,然后让他们同步走,直至 fast 指向链表的末节点,此时 slow 指向需删除节点的前一个节点
- 删除所需删除的节点
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
dummy_head = ListNode(next = head)
slow = dummy_head
fast = dummy_head
while n != 0:
fast = fast.next
n = n - 1
while fast.next != None:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy_head.next
※slow.next = slow.next.next
而非slow.next = fast
是因为,后者只有在 n=2 时成立