编辑代码


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
public class FindFirstNode {
    public static class Node {
        private Integer id;
        private Integer nextId;
        public Node(Integer id, Integer nextId) {
            this.id = id;
            this.nextId = nextId;
        }
        @Override
        public String toString() {
            return String.format("Node(id:%d; nextId:%d)", id, nextId);
        }
    }

    public static int findFirstNode(List<Node> list){
        if(null==list||list.size()==0) {
            return 0;
        }
        Map<Integer, Integer> preMap = new HashMap();

        int tail = 0;
        for(Node n : list) {
            if(n.nextId != null) {
                preMap.putIfAbsent(n.nextId, n.id);
            } else {
                tail = n.id;
            }
        }

        while(preMap.containsKey(tail)) {
            tail = preMap.get(tail);
        }
        
        return tail;
    }

    public static void main(String[] args) {
        ArrayList<Node> list = new ArrayList<>();
        list.add(new Node(2, 3));
        list.add(new Node(3, null));
        list.add(new Node(1, 2));
        list.add(new Node(3, 2));
        System.out.println(findFirstNode(list));
    }
}