【问题标题】:Merging two sorted LinkedList using TreeSet使用 TreeSet 合并两个排序的 LinkedList
【发布时间】:2015-10-01 19:19:45
【问题描述】:

我正在尝试使用 TreeSet 合并两个已排序的 LinkedList,因为它们自己已经对其进行了排序(尽管有一个例外,两个linkedList 都没有公共元素)。这里的问题是,我试图返回的 LinkedList 中附加了一个神秘的“0”,我无法确定。

Node gimmeNode(Node root, TreeSet<Integer> st){
Node temp = root;
Node toPrint = root;
Iterator it = st.iterator();
while(it.hasNext()){
    temp.data = (int) it.next();
    temp.next = new Node();
    temp = temp.next;
}
return root;
}

Node MergeLists(Node headA, Node headB) {
Node root = new Node();
TreeSet<Integer> st = new TreeSet<>();
if(headA==null)
    return headB;
else if(headB==null)
    return headA;
else{

    while(headA != null){
        st.add(headA.data);
        System.out.println("AddedA : " + headA.data);
        headA = headA.next;

    }


    while(headB != null){
        st.add(headB.data);
        System.out.println("AddedB : " + headB.data);
        headB = headB.next;
    }
    root = gimmeNode(root, st);
    return root;
}



}

Output

AddedA : 1
AddedA : 3
AddedA : 5
AddedA : 6
AddedB : 2
AddedB : 4
AddedB : 7
LinkedList : 1 2 3 4 5 6 7 0

【问题讨论】:

    标签: java linked-list treeset


    【解决方案1】:

    gimmeNode 在其末尾有一个 new Node()。这不应该是这种情况 - 它应该指向 null。因此,new Node(),因为它是默认构造的,所以有一个 0。这是你无关的 0。你应该实现一种机制来检查你是否在 TreeSet 的最后一个元素 - 一个微不足道的计数器就可以了。如果你在最后一个元素,不要设置temp.next = new Node();,留下null

    【讨论】:

    • 不会 it.hasNext() 只有在 TreeSet 中还有一个元素时才起作用?像 while(node.next != null) 所以它不应该分配内存,如果它在最后(因为 while 循环根本不会执行)?
    • 是的,但是在 while 循环的最后一次迭代中 - 对于集合中的最后一个元素 - 您设置了 temp.next = new Node();。这个new Node()是你面对的0。
    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    相关资源
    最近更新 更多