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
+ import java .util .Stack ;
2
+
3
+ // Definition for singly-linked list.
4
+ class ListNode {
5
+
6
+ int val ;
7
+ ListNode next ;
8
+
9
+ ListNode () {
10
+ }
11
+
12
+ ListNode (int val ) {
13
+ this .val = val ;
14
+ }
15
+
16
+ ListNode (int val , ListNode next ) {
17
+ this .val = val ;
18
+ this .next = next ;
19
+ }
20
+ }
21
+
22
+ class Solution {
23
+
24
+ public void reorderList (ListNode head ) {
25
+ // ํ์ด: ์ญ์์ผ๋ก ์ ์ฅํ ์คํ์ node๋ค์ ๋ฃ๊ณ , ๊ธฐ์กด node 1๊ฐ/์คํ node 1๊ฐ์ฉ ์ด์ด ๋ถ์ธ๋ค
26
+ // ์คํ์ LIFO๋ก ์ ์ฅ๋๊ธฐ ๋๋ฌธ์, ๋ฌธ์ ์์ ์๊ตฌํ๋ ์์๋๋ก reorderList๋ฅผ ๋ง๋ค ์ ์๋ค
27
+ // TC: O(N)
28
+ // SC: O(2N)
29
+ Stack <ListNode > stack = new Stack <>();
30
+
31
+ var curNode = head ;
32
+ while (curNode != null ) {
33
+ stack .push (curNode );
34
+ curNode = curNode .next ;
35
+ }
36
+
37
+ curNode = head ;
38
+ var halfSize = stack .size () / 2 ; // ํ๋ฒ์ 2๊ฐ์ฉ ์ฐ๊ฒฐํ๊ธฐ๋๋ฌธ์ ์ ๋ฐ๊น์ง๋ง ๋๋ฉด ๋จ
39
+ for (int i =0 ; i <halfSize ; i ++) {
40
+ var top = stack .pop ();
41
+
42
+ var nextNode = curNode .next ;
43
+ curNode .next = top ;
44
+ top .next = nextNode ;
45
+
46
+ curNode = nextNode ;
47
+ }
48
+
49
+ // ๋ง์ฝ ๋
ธ๋์ ๊ฐ์๊ฐ ํ์๋ฉด, ํ๋์ ๋
ธ๋๊ฐ ๋จ๊ธฐ ๋๋ฌธ์ next ๋
ธ๋๋ฅผ null๋ก ์ฒ๋ฆฌํด์ค์ผ ํ๋ค.
50
+ if (curNode != null ) {
51
+ curNode .next = null ;
52
+ }
53
+ }
54
+ }
You canโt perform that action at this time.
0 commit comments