当前位置:网站首页>[leetcode refers to offer 18. Delete the node of the linked list (simple)]

[leetcode refers to offer 18. Delete the node of the linked list (simple)]

2022-04-23 21:21:00 Minaldo7

subject :

Given the head pointer of one-way linked list and the value of a node to be deleted , Define a function to delete the node .

Return the head node of the deleted linked list .

Be careful : This question is different from the original one

Example 1:

Input : head = [4,5,1,9], val = 5
Output : [4,1,9]
explain : Given that the value of your list is 5 Second node of , So after calling your function , The list should be 4 -> 1 -> 9.
Example 2:

Input : head = [4,5,1,9], val = 1
Output : [4,5,9]
explain : Given that the value of your list is 1 The third node of , So after calling your function , The list should be 4 -> 5 -> 9.

explain :

Ensure that the values of nodes in the list are different from each other
If you use C or C++ Language , You don't need to free or delete Deleted node

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
    
    public ListNode deleteNode(ListNode head, int val) {
    
        if(head == null)
            return null;
        ListNode pre = head;
        if(head.val == val){
    
            return head.next;
        }
        while(pre.next!=null && pre!=null){
    
            if(pre.next.val==val){
    
                if(pre.next.next!=null)
                    pre.next = pre.next.next;
                else{
    
                    pre.next = null;
                    break;
                }
            }            
            pre=pre.next;
        }
        return head;
    }
}

Execution results :

 Insert picture description here

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