【发布时间】:2016-11-20 09:20:40
【问题描述】:
我这里有 2 个双链表,我想合并到新的列表中,但轮流创建它时遇到问题。到目前为止,这是我的代码:
class NodeDLL {
public Object data;
public NodeDLL next;
public NodeDLL prev;
public NodeDLL() {
next = null;
}}
public class DoubleLinkList {
private NodeDLL head, tail;
private int counter, pos;
public DoubleLinkList() {
head = null;
tail = null;
counter = -1;
pos = 0;
}
public void InsertFirst(Object dt) {
NodeDLL newNode = new NodeDLL();
newNode.data = dt;
if (head == null) {
newNode.prev = head;
newNode.next = tail;
head = newNode;
tail = newNode;
counter = 0;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
counter++;
}
public static DoubleLinkList combine(DoubleLinkList L1, DoubleLinkList L2) {
DoubleLinkList L3 = new DoubleLinkList();
DoubleLinkList L4 = new DoubleLinkList();
while (L1.head != null) {
L3.InsertFirst(L1.head.data);
L1.head = L1.head.next;
}
while (L2.head != null) {
L3.InsertFirst(L2.head.data);
L2.head = L2.head.next;
}
while (L3.head != null) {
L4.InsertFirst(L3.head.data);
L3.head = L3.head.next;
}
return L4;
}
public void Print(String kom) {
System.out.println(kom);
NodeDLL p = head;
while (p != tail.next) {
System.out.print(p.data + " <-> ");
p = p.next;
}
System.out.println();
}
public static void main(String s[]) {
DoubleLinkList dll2 = new DoubleLinkList();
dll2.InsertFirst("A");
dll2.InsertFirst("B");
dll2.InsertFirst("C");
dll2.InsertFirst("D");
dll2.InsertFirst("E");
dll2.InsertFirst("F");
dll2.Print("Linked List 1");
System.out.println("");
DoubleLinkList dll3 = new DoubleLinkList();
dll3.InsertFirst(1);
dll3.InsertFirst(2);
dll3.InsertFirst(3);
dll3.InsertFirst(4);
dll3.InsertFirst(5);
dll3.InsertFirst(6);
dll3.Print("Linked List 2");
System.out.println("");
DoubleLinkList NewList= DoubleLinkList.combine(dll2, dll3);
NewList.Print("Result");
}}
此代码将显示:
链表 1
F E D C B A
链表 2
6 5 4 3 2 1
结果
F E D C B A 6 5 4 3 2 1
预期输出:
F 6 E 5 D 4 C 3 B 2 A 1
【问题讨论】:
-
欢迎来到 Stack Overflow!请查看我们的SO Question Checklist 以帮助您提出一个好问题,从而得到一个好的答案。
-
发布您的
DoubleLinkedList课程,并为上面的输入发布您的预期输出。A -> 1 -> B -> 2 -> C -> 3 -> D -> 4 -> E -> 5 -> F -> 6.是您的预期输出吗? -
您是否积极处理
next,只产生可用的DoubleLinkLists?尝试更详细地描述by turns:它可能会让您知道如何对其进行编码。 -
@RafiduzzamanSonnet 我已经编辑了我的帖子,希望你能理解我的问题
-
@greybeard 当然不,这只是我代码的一部分。我已经发布了完整的
标签: java algorithm linked-list