Brush questions website: Leetcode
Difficulty: Moderate
Language: Python
Plan : From easy -> to medium -> to hard.
1. 19 Delete the Nth node from the bottom of the linked list
1.1 Topic description
Given a linked list, delete the nth last node of the linked list, and return the head node of the linked list.
- Example 1
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
- Example 2
输入:head = [1], n = 1
输出:[]
- Example 3
输入:head = [1,2], n = 1
输出:[1]
1.2 Thinking and Analysis
(I don't understand this question very well, but it will be clearer after reading the answer!)
Generally, to find a special position in the linked list , first consider using the fast and slow pointer method and find its predecessor. This question says to delete the penultimate n
node, in fact, it can also be understood as deleting the first L-N+1
node.
The linked list must be a way to point to the next one. If you need to delete a node, you need to find its predecessor node. However, when the length of the linked list is 1, that is, only the head node, it has no predecessor and is prone to errors. Usually, a dummy node is added before the head node , and its next
pointer points to the head node of the linked list. That is, there is no need to make special judgment on the head node, otherwise the boundary conditions need to be judged.
head_dumy = ListNode() #添加哑节点
head_dumy.next = head #哑节点指向头节点
slow, fast = head_dummy, head_dummy ##快慢指针指向哑节点
Code idea:Let the fast pointer n
advance , and then the fast and slow pointers advance together until the fast pointer points Null
, then the node pointed to by the slow pointer at this time is the node to be deleted, but it is necessary to know the predecessor node of the deleted node in order to delete it.
Fast pointer advances n steps
while(n!=0): #fast先往前走n步
fast = fast.next
n -= 1
Then, the fast and slow hands move at the same time until the fast hand reaches the end
while(fast.next!=None):
slow = slow.next
fast = fast.next
Then, delete the backdrive node of the slow pointer (that is, let it point to the backdrive node of the backdrive)
slow.next = slow.next.next #删除
The complete code is as follows
# 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: ListNode, n: int) -> ListNode:
head_dummy = ListNode()
head_dummy.next = head
slow, fast = head_dummy, head_dummy
while(n!=0): #fast先往前走n步
fast = fast.next
n -= 1
while(fast.next!=None):
slow = slow.next
fast = fast.next
#fast 走到结尾后,slow的下一个节点为倒数第N个节点
slow.next = slow.next.next #删除
return head_dummy.next
1.3 Summary
The point of this question is to understand what is a linked list? It is different from the list, the length cannot be directly obtained, it is the storage method of each node pointing to the next node. Another concept is that the dummy node points to the head node. The way to delete a node is to let the node it points to skip it.