Skip to content

Commit 36ed55b

Browse files
committed
merge two sorted lists
1 parent 8561368 commit 36ed55b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

merge-two-sorted-lists/se6816.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
연결 리스트를 활용하여, 하나의 리스트를 만드는 방식
3+
시간 복잡도 : O(N+M)
4+
공간 복잡도 : O(1)
5+
*/
6+
class Solution {
7+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
8+
NodeList list=new NodeList();
9+
ListNode temp = null;
10+
while(list1 != null && list2 != null){
11+
if(list1.val >= list2.val){
12+
list2 = merge(list, list2);
13+
}else{
14+
list1 = merge(list, list1);
15+
}
16+
}
17+
while(list1 !=null){
18+
list1 = merge(list, list1);
19+
}
20+
while(list2 != null){
21+
list2 = merge(list, list2);
22+
}
23+
return list.head;
24+
}
25+
public class NodeList {
26+
ListNode head = null;
27+
ListNode tail = null;
28+
public NodeList(){
29+
}
30+
31+
public void add(ListNode tempNode){
32+
if(head == null){
33+
head = tempNode;
34+
tail = head;
35+
}else{
36+
tail.next = tempNode;
37+
tail = tail.next;
38+
}
39+
}
40+
41+
}
42+
43+
public ListNode merge(NodeList list, ListNode target) {
44+
ListNode tempNode = null;
45+
tempNode = target;
46+
list.add(target);
47+
target = target.next;
48+
tempNode.next = null;
49+
return target;
50+
}
51+
}

0 commit comments

Comments
 (0)