File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * function ListNode(val, next) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.next = (next===undefined ? null : next)
6
+ * }
7
+ */
8
+ /**
9
+ * @param {ListNode } head
10
+ * @return {void } Do not return anything, modify head in-place instead.
11
+ */
12
+ var reorderList = function ( head ) {
13
+ if ( ! head ) {
14
+ return null ;
15
+ }
16
+
17
+ const stack = [ ] ;
18
+
19
+ let node = head ;
20
+
21
+ while ( node ) {
22
+ stack . push ( node ) ;
23
+ node = node . next ;
24
+ }
25
+
26
+ const length = stack . length ;
27
+
28
+ node = head ;
29
+ let count = 0 ;
30
+
31
+ while ( count < length ) {
32
+ if ( count % 2 === 0 ) {
33
+ const top = stack . pop ( ) ;
34
+
35
+ top . next = node . next ;
36
+
37
+ node . next = top ;
38
+ }
39
+
40
+ if ( count === length - 1 ) {
41
+ node . next = null ;
42
+ } else {
43
+ node = node . next ;
44
+ }
45
+
46
+ count ++ ;
47
+ }
48
+
49
+
50
+ return head ;
51
+ } ;
52
+
53
+ // 시간복잡도 O(n) -> while문이 링크드리스트의 길이만큼 순회를하기때문에 링크드리스트의 길이만큼 시간이 걸림
54
+ // 공간복잡도 O(n) -> 스택에 모든 노드를 저장하기 때문에 링크드리스트의 길이만큼 공간이 필요
You can’t perform that action at this time.
0 commit comments