Problem: 19. 删除链表的倒数第 N 个结点


文章目录

  • 思路 & 解题方法
  • 复杂度
  • Code


思路 & 解题方法

模拟。

复杂度

时间复杂度:

添加时间复杂度, 示例: 删除链表的倒数第 N 个结点【链表】_链表

空间复杂度:

添加空间复杂度, 示例: 删除链表的倒数第 N 个结点【链表】_链表

Code

# 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]:
        tail = head
        length = 0
        while tail:
            length += 1
            tail = tail.next
        tail = head
        ans = ListNode(0, None)
        p = ans
        for i in range(length):
            if i != length - n:
                t = ListNode(tail.val, None)
                p.next = t
                p = t
            tail = tail.next
        return ans.next