Skip to content

Commit be76c84

Browse files
committed
merge two sorted lists solved
1 parent 5a8b85e commit be76c84

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+
/**
13+
시간복잡도: O(N)
14+
공간복잡도: O(1)
15+
*/
16+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
17+
ListNode answer = new ListNode(-1);
18+
ListNode node = answer;
19+
20+
while(list1 != null && list2 != null) {
21+
if(list1.val < list2.val) {
22+
node.next = list1;
23+
list1 = list1.next;
24+
} else {
25+
node.next = list2;
26+
list2 = list2.next;
27+
}
28+
29+
node = node.next;
30+
}
31+
32+
node.next = list1 != null ? list1 : list2;
33+
34+
return answer.next;
35+
}
36+
}

0 commit comments

Comments
 (0)