Skip to content

Commit f1cdd1e

Browse files
author
jinvicky
committed
merge two sorted list solution
1 parent 4e7bb8d commit f1cdd1e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
3+
ListNode answer = new ListNode();
4+
ListNode mergePointer = answer;
5+
// ๋จธ์ง€๋ฅผ ์ˆ˜ํ–‰ํ•  ํฌ์ธํ„ฐ์™€ ์ •๋‹ต์„ ๋ฐ˜ํ™˜ํ•  ํฌ์ธํ„ฐ ์ด 2๊ฐœ์˜ ํฌ์ธํ„ฐ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.
6+
// ์ดˆ๊ธฐํ™”์—์„œ ์ •๋‹ต ํฌ์ธํ„ฐ์™€ ๋จธ์ง€ ํฌ์ธํ„ฐ๊ฐ€ ๊ฐ™์€ ๋…ธ๋“œ ์ฃผ์†Œ๋ฅผ ๋ฐ”๋ผ๋ณด๊ฒŒ ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
7+
// ๋จธ์ง€ ํฌ์ธํ„ฐ๊ฐ€ ์—ฐ์‚ฐ์„ ๊ณ„์†ํ•˜๋”๋ผ๋„ ์ •๋‹ต ํฌ์ธํ„ฐ์˜ next๋Š” ์ •๋ ฌ๋œ ์ฒซ๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ฌ ๊ฒƒ์ž…๋‹ˆ๋‹ค.
8+
// ๋จธ์ง€ ํฌ์ธํ„ฐ๋Š” ์—ฐ์‚ฐ์„ ๊ณ„์†ํ•˜๋ฉด์„œ ์ฐธ์กฐ ์ฃผ์†Œ๊ฐ€ ๋ณ€๊ฒฝ๋˜๊ธฐ ๋•Œ๋ฌธ์— ๊ทธ ์ž์ฒด๋กœ ๋ฐ˜ํ™˜ํ•˜๋ฉด ์•ˆ๋ฉ๋‹ˆ๋‹ค.
9+
10+
while (list1 != null && list2 != null) {
11+
// list1์˜ ๊ฐ’์ด list2์˜ ๊ฐ’๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด list1์˜ ๋…ธ๋“œ๋ฅผ ๋ณ‘ํ•ฉ
12+
if (list1.val <= list2.val) { // wrong: ๊ฐ’์ด ๋” ์ž‘๊ฑฐ๋‚˜, ๋˜๋Š” ๊ฐ’์ด ๋™์ผํ•  ๊ฒฝ์šฐ list1์„ ์šฐ์„ ์‹œํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
13+
mergePointer.next = list1;
14+
list1 = list1.next;
15+
} else {
16+
// ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด list2์˜ ๋…ธ๋“œ๋ฅผ ๋ณ‘ํ•ฉ
17+
mergePointer.next = list2;
18+
list2 = list2.next;
19+
}
20+
mergePointer = mergePointer.next;
21+
}
22+
23+
// ๋‘ ๋ฆฌ์ŠคํŠธ๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์„ ์ „์ œ๋กœ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ•œ ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด ๋์— ๋„๋‹ฌํ•˜๋ฉด ๋‚˜๋จธ์ง€๋Š” ๊ทธ์ € ํ†ต ๋ถ™์—ฌ๋„ฃ๊ธฐ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค.
24+
// ๋‘ ๋ฆฌ์ŠคํŠธ ์ค‘์—์„œ null์ด ์•„๋‹Œ ๋ฆฌ์ŠคํŠธ ๋…ธ๋“œ๋กœ ๋จธ์ง€ ํฌ์ธํ„ฐ์˜ next์— ์—ฐ๊ฒฐํ•ฉ๋‹ˆ๋‹ค.
25+
if (list1 != null) {
26+
mergePointer.next = list1;
27+
} else {
28+
mergePointer.next = list2;
29+
}
30+
return answer.next;
31+
}
32+
}

0 commit comments

Comments
ย (0)