当前位置:网站首页>Linked list delete nodes in the linked list

Linked list delete nodes in the linked list

2022-06-25 10:06:00 Morris_

LC Delete the nodes in the list

Please write a function , be used for Delete a specific node in the single linked list . When designing functions, you need to pay attention to , You can't access the head node of the linked list head , Direct access only The node to be deleted .

The topic data ensures that the nodes to be deleted Not the end node .

Input :head = [4,5,1,9], node = 5
Output :[4,1,9]
explain : Specifies that the value in the linked list is 5 Second node of , So after calling your function , The list should be 4 -> 1 -> 9

public class ListNode {
    
    ///  Node values 
    public var val: Int
    /// next node 
    public var next: ListNode?
    ///  The node value is passed in during initialization , On initialization next The node is nil
    public init (_ val: Int) {
    
        self.val = val
        self.next = nil
    }
}

Ideas :

General , If you want to delete 5 , Our first thought is to 5 The successor nodes of the predecessor nodes of the node point to 5 Successor node .

In short, it means that 4 The node of next Pointer to 1, Then delete 5 Of next Just a pointer , As shown in the figure below, the line is divided

But the problem is that we don't know 5 Precursor node of this node , because ListNode There is no node stored in the class pre node , Only saved next node .

 Please add a picture description

Another way of thinking , If we change the value of the current node to the value of the next node , Then the current node's next Pointer to lower node , It is as big as expected .

swift Realization

///  Node class 
public class ListNode {
    
    ///  Node values 
    public var val: Int
    /// next node 
    public var next: ListNode?
    ///  The node value is passed in during initialization , On initialization next The node is nil
    public init (_ val: Int) {
    
        self.val = val
        self.next = nil
    }
}

class Solution {
    
    func deleteNode(_ node: ListNode?) {
    
        var tempNode = node?.next
        node?.val = (node?.next!.val)!
        node?.next = node?.next?.next
        tempNode?.val = 0
        tempNode = nil
    }
}
原网站

版权声明
本文为[Morris_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250915051646.html