我想合併兩個有序的單鏈表。我試圖找出問題所在,但我無法找到答案。輸出不是我所期待的。如何合併兩個有序的單鏈表到一個有序列表
第一列表
:下面11-> 12-> 13-> 15-> 17-> 19->空
class Test
{
Node head; // head of list
class Node
{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
void sortedInsert(Node newNode)
{
Node current;
if (head == null || head.data >= newNode.data)
{
newNode.next = head;
head = newNode;
}
else {
current = head;
while (current.next != null && current.next.data < newNode.data)
current = current.next;
newNode.next = current.next;
current.next = newNode;
}
}
Node newNode(int data)
{
Node x = new Node(data);
return x;
}
/* Function to print linked list */
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data+"-> ");
temp = temp.next;
}
System.out.print("null\n");
}
Node mergeLists(Node list1, Node list2) {
Node result;
if (list1 == null) return list2;
if (list2 == null) return list1;
if (list1.data < list2.data) {
result = list1;
result.next = mergeLists(list1.next, list2);
} else {
result = list2;
result.next = mergeLists(list2.next, list1);
}
return result;
}
/* Drier function to test above methods */
public static void main(String args[])
{
Test oneList = new Test();
Test twoList = new Test();
Test joinList = new Test();
Node l1,l2,join;
//First linked list
l1 = oneList.newNode(11);
oneList.sortedInsert(l1);
l1 = oneList.newNode(13);
oneList.sortedInsert(l1);
l1 = oneList.newNode(12);
oneList.sortedInsert(l1);
l1 = oneList.newNode(17);
oneList.sortedInsert(l1);
l1 = oneList.newNode(15);
oneList.sortedInsert(l1);
l1 = oneList.newNode(19);
oneList.sortedInsert(l1);
System.out.println("First List");
oneList.printList();
//Second Linked List
l2 = twoList.newNode(1);
twoList.sortedInsert(l2);
l2 = twoList.newNode(5);
twoList.sortedInsert(l2);
l2 = twoList.newNode(3);
twoList.sortedInsert(l2);
l2 = twoList.newNode(7);
twoList.sortedInsert(l2);
l2 = twoList.newNode(4);
twoList.sortedInsert(l2);
l2 = twoList.newNode(19);
twoList.sortedInsert(l2);
System.out.println("Created Second Linked List");
twoList.printList();
join=joinList.mergeLists(l1,l2);
System.out.println("Merge");
joinList.sortedInsert(join);
joinList.printList();
}
}
OUTPUT 輸出給出
創建第二個鏈接列表
1-> 3-> 4-> 5-> 7-> 19->空
合併
19->空
歡迎來到Stack Overflow!它看起來像你需要學習使用調試器。請幫助一些[互補調試技術](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。如果您之後仍然有問題,請隨時返回更多詳情。 –
不應該合併爲joinList.head = mergLists(oneList.head,twoList.head); ? – rcgldr
你想將兩個排序後的鏈表合併成一個嗎? – thebenman