【leetcode千题】19. 删除链表的倒数第N个节点

    科技2022-07-11  84

    给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

    示例:

    给定一个链表: 1->2->3->4->5, 和 n = 2.

    当删除了倒数第二个节点后,链表变为 1->2->3->5. 说明:

    给定的 n 保证是有效的。

    进阶:

    你能尝试使用一趟扫描实现吗?

    思路:两次遍历

    第一次遍历找到链表的长度 第二次删掉倒数第n个

    # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: l = 1 h1 = head h2 = head while h1.next != None: l+=1 h1 = h1.next l = l-n if l==0: return head.next for i in range(l-1): h2 = h2.next if h2.next == None: h2.next = None else: h2.next = h2.next.next return head

    思路2:双指针一遍遍历

    先让右指针比左指针前n个,然后一起同步右移直到边界 修改左指针即可

    # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: h1 = head h2 = head for i in range(n): h2 = h2.next if h2 == None: return head.next while h2.next!= None: h1 = h1.next h2 = h2.next h1.next = h1.next.next return head
    Processed: 0.014, SQL: 8