File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed 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+ /**
14+ Do not return anything, modify head in-place instead.
15+ */
16+
17+ /**
18+ * ๋ฆฌ์คํธ ์ฌ์ ๋ ฌ ํ๊ธฐ (0 -> n -> 1 -> n-1 -> ...)
19+ * ์๊ณ ๋ฆฌ์ฆ ๋ณต์ก๋
20+ * - ์๊ฐ ๋ณต์ก๋: O(n)
21+ * - ๊ณต๊ฐ ๋ณต์ก๋: O(n)
22+ * @param head
23+ */
24+ function reorderList ( head : ListNode | null ) : void {
25+ if ( ! head || ! head . next ) return ;
26+
27+ const stack : ListNode [ ] = [ ] ;
28+ let node = head ;
29+ while ( node ) {
30+ stack . push ( node ) ;
31+ node = node . next ;
32+ }
33+
34+ let left = 0 ;
35+ let right = stack . length - 1 ;
36+
37+ while ( left < right ) {
38+ // ํ์ฌ ๋
ธ๋์ ๋ค์์ ๋ง์ง๋ง ๋
ธ๋ ์ฐ๊ฒฐ
39+ stack [ left ] . next = stack [ right ] ;
40+ left ++ ;
41+
42+ // ๋จ์ ๋
ธ๋๊ฐ ์์ผ๋ฉด ๋ง์ง๋ง ๋
ธ๋์ ๋ค์์ ๋ค์ ์ผ์ชฝ ๋
ธ๋ ์ฐ๊ฒฐ
43+ if ( left < right ) {
44+ stack [ right ] . next = stack [ left ] ;
45+ right -- ;
46+ }
47+ }
48+
49+ // ๋ง์ง๋ง ๋
ธ๋์ next๋ฅผ null๋ก ์ค์
50+ stack [ left ] . next = null ;
51+ }
You canโt perform that action at this time.
0 commit comments