One, the problem description
1, input two monotonous increment of the list, output two list of linked list after synthesis. The new list is also monotonically increasing.
Second, the program is as follows (Java implementation):
1, non-recursive combined ordered linked list
Import java.util.*;
Class listnode{int val;
ListNode Next;
ListNode (int x) {val=x; } public class test{public ListNode Merge (ListNode node1,listnode node2) {if (node1==null&&n
Ode2==null) {return null;
} if (Node1==null) {return node2;
} if (Node2==null) {return node1; } ListNode Node3=null; This as an offset pointer listnode node4=null;
This is the head pointer while (node1!=null&&node2!=null) {if (node1.val<=node2.val) {
if (node4==null) {node3=node1;
Node4=node1;
else {node3.next=node1;
Node3=node3.next;
} Node1=node1.next; } else {if (node4==null) {node3=node2;
Node4=node2;
else {node3.next=node2;
Node3=node3.next;
} Node2=node2.next;
} if (node1!=null) {node3.next=node1;
} if (node2!=null) {node3.next=node2;
return node4;
public static void Main (String []args) {Test test=new test ();
ListNode node11=new ListNode (1);
ListNode node12=new ListNode (3);
ListNode node13=new ListNode (5);
ListNode node14=new ListNode (7);
ListNode node15=new ListNode (9);
ListNode node21=new ListNode (2);
ListNode node22=new ListNode (4);
ListNode node23=new ListNode (6);
ListNode node24=new ListNode (8);
ListNode node25=new ListNode (10); Node11.next=node12;
Node12.next=node13;
Node13.next=node14;
NODE14.NEXT=NODE15;
Node21.next=node22;
Node22.next=node23;
Node23.next=node24;
Node24.next=node25; ListNode node=test.
Merge (NODE11,NODE22);
while (Node!=null) {System.out.print (node.val+ "->");
Node=node.next; }
}
}
2, recursively merging ordered lists
Import java.util.*;
Class listnode{int val;
ListNode Next;
ListNode (int x) {val=x;
} public class test{public ListNode Merge (ListNode node1,listnode node2) {if (node1==null) {
return node2;
} if (Node2==null) {return node1;
} if (Node1.val<=node2.val) {node1.next=merge (NODE1.NEXT,NODE2);
return node1;
else {node2.next=merge (node1,node2.next);
return node2;
} public static void Main (String []args) {Test test=new test ();
ListNode node11=new ListNode (1);
ListNode node12=new ListNode (3);
ListNode node13=new ListNode (5);
ListNode node14=new ListNode (7);
ListNode node15=new ListNode (9);
ListNode node21=new ListNode (2);
ListNode node22=new ListNode (4);
ListNode node23=new ListNode (6); ListNode node24=new ListNode (8);
ListNode node25=new ListNode (10);
Node11.next=node12;
Node12.next=node13;
Node13.next=node14;
NODE14.NEXT=NODE15;
Node21.next=node22;
Node22.next=node23;
Node23.next=node24;
Node24.next=node25; ListNode node=test.
Merge (NODE11,NODE22);
while (Node!=null) {System.out.print (node.val+ "->");
Node=node.next; }
}
}
Output Result:
1->2->3->4->5->6->7->8->9->10