Skip to content

Commit d756268

Browse files
donghyeon95donghyeon95
authored andcommitted
feat: Merge Two Sorted Lists #224
1 parent 150b12c commit d756268

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
13+
// O(N)
14+
// 2포인터로 지나가용 하면 되는 문제
15+
ListNode result = new ListNode();
16+
ListNode nowNode = result;
17+
18+
19+
while (list1!=null || list2!=null) {
20+
int first = list1==null? 101: list1.val;
21+
int second = list2==null? 101: list2.val;
22+
23+
if (first < second) {
24+
nowNode.next = new ListNode(first);
25+
nowNode = nowNode.next;
26+
list1 = list1.next;
27+
} else {
28+
nowNode.next = new ListNode(second);
29+
nowNode = nowNode.next;
30+
list2 = list2.next;
31+
}
32+
}
33+
34+
return result.next;
35+
}
36+
}

0 commit comments

Comments
 (0)