给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
image.png
解题思路:
slow.next=slow.next.next即可。Python3代码:
# 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: ListNode, n: int) -> ListNode:
        pre = ListNode(0)
        pre.next = head
        slow, fast = pre, pre
        while n>0:
            n-=1
            fast = fast.next
        
        while fast.next:
            slow = slow.next 
            fast = fast.next
        
        slow.next = slow.next.next
        return pre.next
原文:https://www.cnblogs.com/ecplko/p/13917714.html