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

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

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

import java.util.Scanner; 
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int num = in.nextInt();
            int head = in.nextInt();
            int[][] arr = new int[num-1][2];
            for(int i=0;i<num-1;i++){
                arr[i][0] = in.nextInt();
                arr[i][1] = in.nextInt();
            }
            int delete = in.nextInt();
            solution(arr,head,delete);
        }
    }

    public static class LinkNode {
        public int val;
        public LinkNode next;
        public LinkNode(int val){
            this.val = val;
        }
    }

    public static void solution(int[][] arr,int headVal,int deleteVal){
        LinkNode head = new LinkNode(headVal);
        Map<Integer,LinkNode> nodeMap = new HashMap<>();
        nodeMap.put(headVal, head);
        // build link table
        for(int i=0;i<arr.length;i++) {
            LinkNode newNode = new LinkNode(arr[i][0]);
            LinkNode preNode = nodeMap.get(arr[i][1]);
            newNode.next = preNode.next;
            preNode.next = newNode;
            nodeMap.put(arr[i][0], newNode);
        }
        // delete node
        StringBuffer sb=new StringBuffer();
        while(head!=null) {
            if(head.val!=deleteVal){
                sb.append(head.val+" ");
            }
            head=head.next;
        }
        System.out.println(sb.toString());
    }
}

全部评论

相关推荐

哇哇的菜鸡oc:他这不叫校招offer,而是实习offer
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务