19. 删除链表的倒数第 N 个结点(中等)-链表

2023-05-24  本文已影响0人  MatrixZ

给你一个链表,删除链表的倒数第 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]:

        # 倒数第n个节点,就是正数N-n + 1个节点
        dummy = ListNode()
        length = 0
        cur = head
        while cur:
            length += 1
            cur = cur.next
        
        target_len = length - n + 1
        cur = head
        dummy.next = cur
        prev = dummy
        i = 1
        while cur:
            if i == target_len:
                next = cur.next
                prev.next = next

                break
            i += 1
            prev = prev.next
            cur = cur.next
            
        
        return dummy.next
上一篇 下一篇

猜你喜欢

热点阅读