Rich LeetCode --- 19. Delete the Nth node from the bottom of the linked list

Title description:

Given a linked list, delete the nth node from the bottom of the linked list, and return the head node of the linked list.

Example:

Given a linked list: 1->2->3->4->5, and n = 2.

When the penultimate node is deleted, the linked list becomes 1->2->3->5.

Explanation: The given n guarantee is valid.


Problem solving idea 1:

The speed pointer is mainly divided into the following three steps:

  1. Fast pointer go n steps
  2. The fast and slow pointers move at the same time until the fast pointer reaches the tail node, at which time slow reaches the node before the Nth node from the bottom
  3. Delete node and reconnect

Code 1:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def removeNthFromEnd(self, head, n):
        dummy = ListNode(0)
        dummy.next = head 
        
        # step1: 快指针先走n步
        slow, fast = dummy, dummy
        for _ in range(n):
            fast = fast.next 

        # step2: 快慢指针同时走,直到fast指针到达尾部节点,此时slow到达倒数第N个节点的前一个节点
        while fast and fast.next:
            slow, fast = slow.next, fast.next
        
        #step3: 删除节点,并重新连接
        slow.next = slow.next.next 
        return dummy.next

Problem solving idea 2:

Loop iteration-find length-n nodes, mainly divided into the following three steps:

  1. Get the length of the linked list
  2. Find the node before the Nth node from the bottom
  3. Delete node and reconnect

Code 2:

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        dummy = ListNode(0)
        dummy.next = head 

        # step1: 获取链表长度
        cur, length = head, 0 
        while cur:
            length += 1
            cur = cur.next 
        
        # step2: 找到倒数第N个节点的前面一个节点
        cur = dummy
        for _ in range(length - n):
            cur = cur.next
        
        # step3: 删除节点,并重新连接
        cur.next = cur.next.next
        return dummy.next 

Problem solving idea 3:

Recursive iteration-when backtracking, count nodes:


Code 3:

class Solution:  
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if not head: 
            self.count = 0
            return head  
        head.next = self.removeNthFromEnd(head.next, n) # 递归调用
        self.count += 1 # 回溯时进行节点计数
        return head.next if self.count == n else head 

Reference link:

https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/san-chong-fang-fa-shan-chu-dao-shu-di-nge-jie-dian/


Question source:

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

Guess you like

Origin blog.csdn.net/weixin_43283397/article/details/109346694