Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5d5f2b8

Browse files
LC#21 merge two sorted linkedlists, 2 approaches, recursive and iterative
1 parent 7e8bd13 commit 5d5f2b8

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package LinkedList;
2+
3+
public class MergeTwoSortedLists21 {
4+
5+
public class ListNode {
6+
int val;
7+
ListNode next;
8+
9+
ListNode() {
10+
}
11+
12+
ListNode(int val) {
13+
this.val = val;
14+
}
15+
16+
ListNode(int val, ListNode next) {
17+
this.val = val;
18+
this.next = next;
19+
}
20+
}
21+
22+
// recursive
23+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
24+
25+
return merge(list1, list2);
26+
}
27+
28+
private ListNode merge(ListNode list1, ListNode list2) {
29+
30+
if (list1 == null)
31+
return list2;
32+
if (list2 == null)
33+
return list1;
34+
35+
if (list1.val < list2.val) {
36+
list1.next = merge(list1.next, list2);
37+
return list1;
38+
} else {
39+
list2.next = merge(list1, list2.next);
40+
return list2;
41+
}
42+
}
43+
44+
// iterative
45+
public ListNode mergeTwoListsIterative(ListNode list1, ListNode list2) {
46+
if (list1 == null)
47+
return list2;
48+
if (list2 == null)
49+
return list1;
50+
51+
ListNode mergedAns;
52+
ListNode tail;
53+
54+
if (list1.val < list2.val) {
55+
mergedAns = list1;
56+
tail = list1;
57+
list1 = list1.next;
58+
} else {
59+
mergedAns = list2;
60+
tail = list2;
61+
list2 = list2.next;
62+
}
63+
64+
while (list1 != null && list2 != null) {
65+
if (list1.val < list2.val) {
66+
tail.next = list1;
67+
tail = list1;
68+
list1 = list1.next;
69+
} else {
70+
tail.next = list2;
71+
tail = list2;
72+
list2 = list2.next;
73+
}
74+
}
75+
76+
if (list1 == null)
77+
tail.next = list2;
78+
79+
if (list2 == null)
80+
tail.next = list1;
81+
82+
return mergedAns;
83+
}
84+
}

0 commit comments

Comments
(0)

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /