Skip to content

Commit 7d409d8

Browse files
committed
Solution merge - two -sorted - list
1 parent 98e52e7 commit 7d409d8

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//
2+
// Merge_Two_Sorted_Lists.swift
3+
// Algorithm
4+
//
5+
// Created by ์•ˆ์„ธํ›ˆ on 4/22/25.
6+
//
7+
8+
/**
9+
* Definition for singly-linked list.
10+
* public class ListNode {
11+
* public var val: Int
12+
* public var next: ListNode?
13+
* public init() { self.val = 0; self.next = nil; }
14+
* public init(_ val: Int) { self.val = val; self.next = nil; }
15+
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
16+
* }
17+
*/
18+
class Solution {
19+
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
20+
//list1, list2๊ฐ€ nil์ผ ๊ฒฝ์šฐ๋ฅผ ๋Œ€๋น„ํ•ด ์ „์ฒ˜๋ฆฌ
21+
guard list1 != nil else { return list2 }
22+
guard list2 != nil else { return list1 }
23+
24+
//์ดˆ๊ธฐํ™” Node
25+
var head : ListNode? = ListNode(0)
26+
27+
//์—ฐ์‚ฐ์„ ์œ„ํ•œ Node
28+
var current = head
29+
var l1 = list1
30+
var l2 = list2
31+
32+
while l1 != nil && l2 != nil{ //๋‘ ๋ฆฌ์ŠคํŠธ ๋ชจ๋‘ nil์ด ์•„๋‹ ๊ฒฝ์šฐ์—๋งŒ ์—ฐ์‚ฐ.
33+
if let val1 = l1?.val, let val2 = l2?.val{ //๋น„๊ตํ•  node๋ฅผ ๊ฐ๊ฐ list1?.val, list2?.val๋กœ ์•ˆ์ „ํžˆ ๋ฐ”์ธ๋”ฉ
34+
if val1 < val2{ //๋‘ ์ˆ˜ ๋น„๊ต
35+
current?.next = ListNode(val1) //reusltNode์˜ ๋‹ค์Œ์„ ์ž‘์€์ˆ˜๋กœ ์„ค์ •
36+
l1 = l1?.next //์—ฐ์‚ฐ ํ›„ ๋‹ค์Œ ๋…ธ๋“œ๋กœ ๋„˜๊น€
37+
}else{
38+
current?.next = ListNode(val2) //reusltNode์˜ ๋‹ค์Œ์„ ์ž‘์€์ˆ˜๋กœ ์„ค์ •
39+
l2 = l2?.next //์—ฐ์‚ฐ ํ›„ ๋‹ค์Œ ๋…ธ๋“œ๋กœ ๋„˜๊น€
40+
}
41+
current = current?.next //์—ฐ์‚ฐ ํ›„ ๊ฒฐ๊ณผ ๋…ธ๋“œ๋„ ๋‹ค์Œ์œผ๋กœ ๋„˜๊น€
42+
}
43+
}
44+
current?.next = l1 ?? l2 //while์ด ๋๋‚œ ํ›„ ๋‚จ์€ ๋…ธ๋“œ๋Š” ๋’ค์— ๋ถ™ํž˜
45+
46+
return head?.next
47+
}
48+
}

0 commit comments

Comments
ย (0)