Skip to content

Commit 3c37d64

Browse files
committed
두 리스트 머지
1 parent 20ee53a commit 3c37d64

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

MergeTwoLists/ListNode.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
public class ListNode {
2+
int val;
3+
ListNode next;
4+
5+
ListNode() {}
6+
7+
ListNode(int val) { this.val = val; }
8+
9+
ListNode(int val, ListNode next) {
10+
this.val = val;
11+
this.next = next;
12+
}
13+
14+
@Override
15+
public String toString() {
16+
return val + ",";
17+
}
18+
}

MergeTwoLists/MergeTwoLists.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
public class MergeTwoLists {
2+
public static void main(String[] args) {
3+
ListNode l1 = new ListNode(1, new ListNode(2, new ListNode(4)));
4+
ListNode l2 = new ListNode(1, new ListNode(3, new ListNode(4)));
5+
System.out.println(new MergeTwoLists().mergeTwoLists(l1, l2));
6+
}
7+
8+
9+
//my solution
10+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
11+
ListNode head = null;
12+
ListNode mergeList;
13+
14+
if (l1 == null && l2 == null)
15+
return head;
16+
else if (l1 == null || l2 == null) {
17+
if (l1 == null)
18+
return l2;
19+
else
20+
return l1;
21+
} else {
22+
if (l1.val <= l2.val) {
23+
mergeList = l1;
24+
l1 = l1.next;
25+
} else {
26+
mergeList = l2;
27+
l2 = l2.next;
28+
}
29+
}head = mergeList;
30+
31+
while (l1 != null || l2 != null) {
32+
if (l1 == null) {
33+
mergeList.next = l2;
34+
l2 = l2.next;
35+
} else if (l2 == null) {
36+
mergeList.next = l1;
37+
l1 = l1.next;
38+
} else if (l1.val <= l2.val) {
39+
mergeList.next = l1;
40+
l1 = l1.next;
41+
} else {
42+
mergeList.next = l2;
43+
l2 = l2.next;
44+
}
45+
mergeList = mergeList.next;
46+
}
47+
return head;
48+
}
49+
}
50+
51+
/* best solution_USE recursive
52+
class Solution {
53+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
54+
if (l1 == null) {
55+
return l2;
56+
} else if (l2 == null) {
57+
return l1;
58+
} else if (l1.val < l2.val) {
59+
l1.next = mergeTwoLists(l1.next, l2);
60+
return l1;
61+
} else {
62+
l2.next = mergeTwoLists(l1, l2.next);
63+
return l2;
64+
}
65+
}
66+
}
67+
*/

0 commit comments

Comments
 (0)