Skip to content

Commit 68e5d8a

Browse files
authored
Create MergeTwoSortedLists.java
1 parent 3b1c181 commit 68e5d8a

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

MergeTwoSortedLists.java

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
Merge two sorted linked lists and return it as a new list. The new list should be made by
3+
splicing together the nodes of the first two lists.
4+
*/
5+
public class MergeTwoSortedLists {
6+
public static void main(String[] args){
7+
ListNode n1 = new ListNode(1);
8+
ListNode n11 = new ListNode(2);
9+
ListNode n111 = new ListNode(4);
10+
n1.next = n11;
11+
n11.next = n111;
12+
ListNode n2 = new ListNode(1);
13+
ListNode n22 = new ListNode(3);
14+
ListNode n222 = new ListNode(4);
15+
n2.next = n22;
16+
n22.next = n222;
17+
18+
ListNode node = mergeTwoLists(n1, n2);
19+
printListValues(node);
20+
}
21+
22+
private static void printListValues(ListNode node) {
23+
while(node!=null){
24+
System.out.print(node.val);
25+
if(node.next!=null){
26+
System.out.print("->");
27+
}
28+
node = node.next;
29+
}
30+
}
31+
32+
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
33+
if(l1==null && l2!=null) return l2;
34+
if(l2==null && l1!=null) return l1;
35+
if(l2==null && l1==null) return null;
36+
ListNode node = (l1.val < l2.val) ? l1 : l2;
37+
if(l1.val < l2.val){
38+
l1 = l1.next;
39+
}
40+
else{
41+
l2 = l2.next;
42+
}
43+
44+
ListNode parent = node;
45+
while (l1!=null || l2!=null){
46+
if(l1!=null && l2==null){
47+
parent.next = new ListNode(l1.val);
48+
l1 = l1.next;
49+
}
50+
else if(l2!=null && l1==null){
51+
parent.next = new ListNode(l2.val);
52+
l2 = l2.next;
53+
}
54+
else{
55+
parent.next = new ListNode(Integer.min(l1.val, l2.val));
56+
if(l1.val < l2.val) {
57+
l1 = l1.next;
58+
} else {
59+
l2 = l2.next;
60+
}
61+
}
62+
parent = parent.next;
63+
}
64+
65+
return node;
66+
}
67+
public static class ListNode {
68+
int val;
69+
ListNode next;
70+
ListNode(int x) { val = x; }
71+
}
72+
}

0 commit comments

Comments
 (0)