题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

import java.util.*;

class ListNode{
    int val;
    ListNode next;

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

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        
        ListNode head = new ListNode(in.nextInt());

        for(int i = 0; i < n - 1; i++){
            int cur = in.nextInt();
            int pre = in.nextInt();
            head = insert(head,cur,pre);
        }

        int r_val = in.nextInt();
        head = remove(head,r_val);

        while(head != null){
            System.out.print(head.val + " ");
            head = head.next;
        }
    }

    private static ListNode insert(ListNode head,int cur, int pre){
        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        while(head.val != pre){
            head = head.next;
        }

        ListNode n_Node = new ListNode(cur);
        n_Node.next = head.next;
        head.next = n_Node;

        return dummy.next;
    }

    private static ListNode remove(ListNode head,int val){

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;

        while(pre.next.val != val){
            pre = pre.next;
        }

        pre.next = pre.next.next;

        return dummy.next;
    }
}

全部评论

相关推荐

头像
06-04 19:10
Java
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务