19. Remove Nth Node From End of List(移除倒数第N的结点, 快慢指针)
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.
思路:
利用快指针先走n步,找到倒数第n个节点
然后删除。
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: fake = ListNode(-1,head) pre = fake fast = head for i in range(n): fast = fast.next slow = head while fast: slow = slow.next fast = fast.next pre = pre.next pre.next = slow.next slow.next = None return fake.next