Delete all nodes with specified values in the linked list

Ideas

  • If the linked list is empty , return null
  • Define two nodes, the node to be deleted and the previous node of the node to be deleted
  • As shown in the figure below, each color represents a different step of operation

  • We are equivalent to judging from the second node, so we must finally determine whether the first node meets the deletion condition . In the above linked list, it is obviously satisfied, so let head point to the next node of the first node, and finally return head, that is, the first node is deleted

Code

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

public class Test {
    //创建一个链表
    public static ListNode init(){
        ListNode node1=new ListNode(1);
        ListNode node2=new ListNode(1);
        ListNode node3=new ListNode(2);
        ListNode node4=new ListNode(1);
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        node4.next=null;
        return node1;
    }
    //打印链表
    private static void printNodeList(ListNode head) {
        for(ListNode cur=head;cur!=null;cur=cur.next){
            System.out.print(cur.val+"  ");
        }
        System.out.println();
    }
    //删除元素
    public static ListNode removeElements(ListNode head, int val) {
        if(head==null){
            return null;
        }
        ListNode prev=head;//待删节点的前一个节点
        ListNode cur=prev.next;//待删节点
        for(;cur!=null;){
            if(cur.val==val){
                prev.next=cur.next;
                cur=cur.next;
            }else{
                prev=cur;
                cur=cur.next;
            }
        }
        if(head.val==val){
            head=head.next;
        }
        return head;
    }
    public static void main(String[] args) {
        ListNode head=init();
        //删除前
        printNodeList(head);
        //删除后
        head=removeElements(head,1);
        printNodeList(head);
    }
}

result

Guess you like

Origin blog.csdn.net/weixin_43939602/article/details/113868021