File tree 2 files changed +78
-0
lines changed
2 files changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ # O(n + m) time, n = list1의 노드 수 / m = list2의 노드 수
2
+ # O(1) space, 연결된 새 리스트는 기존 노드들을 재사용해서 만듬
3
+
4
+ # Definition for singly-linked list.
5
+ # class ListNode:
6
+ # def __init__(self, val=0, next=None):
7
+ # self.val = val
8
+ # self.next = next
9
+
10
+ class ListNode :
11
+ def __init__ (self , val = 0 , next = None ):
12
+ self .val = val
13
+ self .next = next
14
+
15
+ class Solution :
16
+ def mergeTwoLists (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
17
+ dummy = ListNode ()
18
+ tail = dummy
19
+
20
+ while list1 and list2 :
21
+ if list1 .val < list2 .val :
22
+ tail .next = list1
23
+ list1 = list1 .next
24
+ else :
25
+ tail .next = list2
26
+ list2 = list2 .next
27
+ tail = tail .next
28
+
29
+ if list1 :
30
+ tail .next = list1
31
+ if list2 :
32
+ tail .next = list2
33
+ return dummy .next
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * class ListNode {
4
+ * val: number
5
+ * next: ListNode | null
6
+ * constructor(val?: number, next?: ListNode | null) {
7
+ * this.val = (val===undefined ? 0 : val)
8
+ * this.next = (next===undefined ? null : next)
9
+ * }
10
+ * }
11
+ */
12
+
13
+ class ListNode {
14
+ val : number ;
15
+ next : ListNode | null ;
16
+ constructor ( val ?: number , next ?: ListNode | null ) {
17
+ this . val = val === undefined ? 0 : val ;
18
+ this . next = next === undefined ? null : next ;
19
+ }
20
+ }
21
+
22
+ function mergeTwoLists (
23
+ list1 : ListNode | null ,
24
+ list2 : ListNode | null
25
+ ) : ListNode | null {
26
+ const dummy = new ListNode ( ) ;
27
+ let tail = dummy ;
28
+ while ( list1 !== null && list2 !== null ) {
29
+ if ( list1 . val < list2 . val ) {
30
+ tail . next = list1 ;
31
+ list1 = list1 . next ;
32
+ } else {
33
+ tail . next = list2 ;
34
+ list2 = list2 . next ;
35
+ }
36
+ tail = tail . next ;
37
+ }
38
+ if ( list1 !== null ) {
39
+ tail . next = list1 ;
40
+ }
41
+ if ( list2 !== null ) {
42
+ tail . next = list2 ;
43
+ }
44
+ return dummy . next ;
45
+ }
You can’t perform that action at this time.
0 commit comments