leetcode [linked list - simple] 203. Remove linked list elements

Keywords: data structure leetcode linked list

preface

Hello, I'm long Lu. I'm just a junior now. I'm working on the back end and occasionally on the front end. Now the main language is Java. For a long time before, I was learning some technologies of web development. I haven't studied and brushed questions like data structures and algorithms for a long time. I plan to pick them up and learn and do it well during this time.

During this period, I also happened to see that Cao Mao Lufei's blog added a self-study group. I happened to see that the blogger organized a leetcode question swiping and punching activity in the group. I also participated in it for one month. I intend to spend some time doing some questions every day and record them through a blog.

At present, there is a Github warehouse with leetcode: Code Capriccio leetcode brush questions , it is currently a linked list topic.


subject

Title source leetcode

leetcode address: Remove linked list elements , difficulty: simple.

Title Description (from leetcode):

Give you a head node of the linked list head And an integer val ,Please delete all items in the linked list Node.val == val And returns a new header node.
 
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
 Output:[1,2,3,4,5]

Example 2:
Input: head = [], val = 1
 Output:[]

Example 3:
Input: head = [7,7,7,7], val = 7
 Output:[]
 
Tips:
The number of nodes in the list is in the range [0, 104] within
1 <= Node.val <= 50
0 <= val <= 50

Local debug code:

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution{
    //Business code (leetcode core method code)
    public ListNode removeElements(ListNode head, int val) {
		...
    }

    public static void main(String[] args) {
        ListNode node7 = new ListNode(6, null);
        ListNode node6 = new ListNode(5, node7);
        ListNode node5 = new ListNode(4, node6);
        ListNode node4 = new ListNode(3, node5);
        ListNode node3 = new ListNode(6, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
        ListNode listNode = new Solution().removeElements(node1, 6);
        printList(listNode);//Print node
    }

    private static void printList(ListNode listNode) {
        if(listNode == null){
            return;
        }
        System.out.print("[");
        while(listNode != null){
            System.out.print(listNode.val);
            if(listNode.next != null){
                System.out.print(",");
            }
            listNode = listNode.next;
        }
        System.out.print("]");
    }


}

Problem solution

NO1: violent solution

There is no idea. Just go through the wave first and run the program again first.

Idea: create a new node and traverse the original linked list= Re create the linked list node, mount it to the next of the new node, and finally return the new node.

  • This method is a little troublesome. You need to consider a variety of situations, and will frequently create new linked lists. See the notes below for details.

code:

public ListNode removeElements(ListNode head, int val) {
    //If the header node is null or the next node of the header node is null and the current node = = Val (in the case of one node), null is returned
    if(head == null || (head.next == null && head.val == val)){
        return null;
    }
    //In case of one or more nodes
    ListNode newHeadNode = null;
    //If it is the first node= val builds an instance
    if(head.val != val){
        newHeadNode = new ListNode(head.val,null);
    }
    //Current node, front node
    ListNode curNode = newHeadNode;
    ListNode nextNode = head.next;
    //Traversal linked list
    while(nextNode!=null){
        if(nextNode.val != val){
            //The first node val before processing= For newHeadNode
            if(newHeadNode == null){
                newHeadNode = new ListNode(nextNode.val,null);
                curNode = newHeadNode;
            }else{
                //After some= Re create the data object and mount it to the newly formed node
                curNode.next = new ListNode(nextNode.val,null);;
                curNode = curNode.next;
            }
        }
        nextNode = nextNode.next;
    }
    return newHeadNode;
}


NO2: set virtual node

After the violence solution passed, I went to see the ideas of other solutions. Compared with the previous violence method, I always felt that there was something missing, resulting in so many code judgment conditions (the first! = val node). Among them, the way to set virtual nodes can well solve my above problems.

Idea: set a virtual node (core) and make the original head node its post node. Similarly, set a pre node and the node that traverses the linked list later (it will be updated every time). Judge whether the node traversed every time = val and replace the next of the pre node. Finally, the node pointed to by the next of the virtual node is returned.

code:

//Set virtual node
public ListNode removeElements(ListNode head, int val) {
    //To save memory consumption, you can end the method in advance
    if(head == null){
        return null;
    }
    ListNode dummy = new ListNode(-1,head);
    ListNode pre = dummy;//Front node
    ListNode cur = head;//Loop traversal node
    while(cur!=null){
        if(cur.val == val){
            pre.next = cur.next;  //This is equivalent to deleting the current node
        }else{ 
            pre = cur; //Move the corresponding front node
        }
        cur = cur.next;
    }
    return dummy.next;
}


NO3: do not set virtual node

Idea: in fact, it is consistent with the idea of NO2 above, except that a virtual node is not directly created here. Instead, when entering the method, all conforming elements of the head node are removed to make it a virtual node. The subsequent operations are the same as before.

code:

//Do not set virtual node
public ListNode removeElements(ListNode head, int val) {
    //Screen out non-conforming elements
    while(head!=null && head.val == val){
        head = head.next;
    }
    if(head == null){
        return null;
    }
    //Current head.val= Val, we can directly traverse next
    ListNode pre = head;
    ListNode cur = head.next;
    while( cur != null){
        if(cur.val == val){
            pre.next = cur.next;  //Equivalent to delete operation
        }else{
            pre = cur;
        }
        cur = cur.next;
    }
    return head;
}


reference material

[1]. leetcode problem solving

[2]. Code capriccio-203. Remove linked list elements


I am a long way. Thank you for your patience in reading. If you have any questions, please point them out and I will actively adopt them!
Welcome to my official account, long road Java, sharing Java learning articles and related materials.
Q group: 851968786 we can discuss and study together
Note: it can be reproduced, and the article link needs to be attached

Posted by gplaurin on Fri, 15 Oct 2021 10:14:34 -0700