Skip to content

Commit a440515

Browse files
committed
feat: week04 merge-two-sorted-lists
1 parent 87d975c commit a440515

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* ๊ณ ์ƒํ•œ ์ด์œ : ListNode ์˜ ์‹œ์ž‘์ ์„ ๋”ฐ๋กœ ๋‘ฌ์•ผ ํ•˜๋Š” ๊ฒƒ!
3+
*
4+
* ListNode dummy = new ListNode(0); // ์‹œ์ž‘์ 
5+
* ListNode output = dummy; // ์‹œ์ž‘์  ๋’ค์— ์‹ค์ œ ์ž‘์—…์šฉ ํฌ์ธํ„ฐ
6+
*
7+
*
8+
* Definition for singly-linked list.
9+
* public class ListNode {
10+
* int val;
11+
* ListNode next;
12+
* ListNode() {}
13+
* ListNode(int val) { this.val = val; }
14+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
15+
* }
16+
*/
17+
class Solution {
18+
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
19+
// ๊ธธ์ด๊ฐ€ ๋‘˜๋‹ค null ์ด๋ฉด, return null
20+
if (list1 == null && list2 == null) return null;
21+
22+
ListNode dummy = new ListNode(0); // ์‹œ์ž‘์ 
23+
ListNode output = dummy; // ์‹œ์ž‘์  ๋’ค์— ์‹ค์ œ ์ž‘์—…์šฉ ํฌ์ธํ„ฐ
24+
25+
while(list1 != null && list2 != null) {
26+
27+
if (list1.val < list2.val) {
28+
output.next = list1;
29+
list1 = list1.next; // list1 ํฌ์ธํ„ฐ ์ด๋™
30+
} else {
31+
output.next = list2;
32+
list2 = list2.next; // list2 ํฌ์ธํ„ฐ ์ด๋™
33+
}
34+
output = output.next; // output ํฌ์ธํ„ฐ ์ด๋™
35+
}
36+
37+
if (list1 != null) {
38+
output.next = list1;
39+
}
40+
if (list2 != null) {
41+
output.next = list2;
42+
}
43+
44+
return dummy.next;
45+
}
46+
}

0 commit comments

Comments
ย (0)