File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * TC: O(N)
3+ * 1번에서 절반 길이만큼 순회
4+ * 2번에서 절반 길이만큼 순회
5+ * 3번에서 절반 길이만큼 순회
6+ *
7+ * SC: O(1)
8+ * linked list의 node를 가리키는 포인터를 가지고 활용하므로 linked list의 길이와 무관한 공간 복잡도를 갖습니다.
9+ *
10+ * N: linked list length
11+ */
12+
13+ /**
14+ * Definition for singly-linked list.
15+ * function ListNode(val, next) {
16+ * this.val = (val===undefined ? 0 : val)
17+ * this.next = (next===undefined ? null : next)
18+ * }
19+ */
20+ /**
21+ * @param {ListNode } head
22+ * @return {void } Do not return anything, modify head in-place instead.
23+ */
24+ var reorderList = function ( head ) {
25+ // 1. linked list 절반 위치 구하기
26+ let slow = head ;
27+ let fast = head ;
28+
29+ while ( fast && fast . next ) {
30+ slow = slow . next ;
31+ fast = fast . next . next ;
32+ }
33+
34+ // 2. 후반 linked list 순서 뒤집기
35+ let halfStartTemp = slow . next ;
36+ let halfStart = null ;
37+ // 절반을 기준으로 linked list 끊기
38+ slow . next = null ;
39+
40+ while ( halfStartTemp ) {
41+ const temp = halfStartTemp . next ;
42+ halfStartTemp . next = halfStart ;
43+ halfStart = halfStartTemp ;
44+ halfStartTemp = temp ;
45+ }
46+
47+ // 3. 두 리스트 합치기
48+ while ( head && halfStart ) {
49+ const headTemp = head . next ;
50+ const halfStartTemp = halfStart . next ;
51+ head . next = halfStart ;
52+ halfStart . next = headTemp ;
53+ head = headTemp ;
54+ halfStart = halfStartTemp ;
55+ }
56+ } ;
You can’t perform that action at this time.
0 commit comments