Skip to content

Latest commit

 

History

History
37 lines (33 loc) · 914 Bytes

19.md

File metadata and controls

37 lines (33 loc) · 914 Bytes

题目地址

https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

解答1

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        """ 删除链表的倒数第N个节点 """

        def index(node):
            if not node:
                return 0
            i = index(node.next) + 1
            if i > n:
                node.next.val = node.val
            return i

        index(head)
        return head.next

解答2

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        """ 删除链表的倒数第N个节点 """
        fast = slow = head
        for _ in range(n):
            fast = fast.next
        if not fast:
            return head.next
        while fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return head