File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ class ListNode {
2
+ val : number ;
3
+ next : ListNode | null ;
4
+ constructor ( val ?: number , next ?: ListNode | null ) {
5
+ this . val = val === undefined ? 0 : val ;
6
+ this . next = next === undefined ? null : next ;
7
+ }
8
+ }
9
+
10
+ /**
11
+ Do not return anything, modify head in-place instead.
12
+ */
13
+
14
+ function reverseList ( head : ListNode | null ) {
15
+ let prev : ListNode | null = null ;
16
+ let cur : ListNode | null = head ;
17
+
18
+ while ( cur ) {
19
+ const next = cur . next ;
20
+ cur . next = prev ;
21
+ prev = cur ;
22
+ cur = next ;
23
+ }
24
+
25
+ return prev ;
26
+ }
27
+
28
+ function reorderList ( head : ListNode | null ) : void {
29
+ if ( ! head || ! head . next ) return ;
30
+
31
+ // 1. 중간 지점 찾기
32
+ let slow : ListNode | null = head ;
33
+ let fast : ListNode | null = head ;
34
+
35
+ while ( fast && fast . next ) {
36
+ slow = slow ! . next ;
37
+ fast = fast . next . next ;
38
+ }
39
+
40
+ // 2. 리스트 절단
41
+ const secondHead = slow ! . next ;
42
+ slow ! . next = null ;
43
+
44
+ // 3. 뒤쪽 리스트 뒤집기
45
+ let second : ListNode | null = reverseList ( secondHead ) ;
46
+
47
+ // 4. 병합
48
+ let first : ListNode | null = head ;
49
+
50
+ while ( second ) {
51
+ let tmp1 = first ! . next ;
52
+ let tmp2 = second . next ;
53
+
54
+ first ! . next = second ;
55
+ second . next = tmp1 ;
56
+
57
+ first = tmp1 ;
58
+ second = tmp2 ;
59
+ }
60
+ }
You can’t perform that action at this time.
0 commit comments