File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ //
2
+ // 143. Reorder List
3
+ // https://leetcode.com/problems/reorder-list/description/
4
+ // Dale-Study
5
+ //
6
+ // Created by WhiteHyun on 2024/06/10.
7
+ //
8
+
9
+ /**
10
+ * Definition for singly-linked list.
11
+ * public class ListNode {
12
+ * public var val: Int
13
+ * public var next: ListNode?
14
+ * public init() { self.val = 0; self.next = nil; }
15
+ * public init(_ val: Int) { self.val = val; self.next = nil; }
16
+ * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
17
+ * }
18
+ */
19
+ class Solution {
20
+ func reorderList( _ head: ListNode ? ) {
21
+ guard head? . next != nil else { return }
22
+
23
+ var nodeList : [ ListNode ] = [ ]
24
+ var tempNode = head
25
+
26
+ // 1. 각 노드를 선형으로 확인하며 리스트에 추가
27
+ while let node = tempNode {
28
+ nodeList. append ( node)
29
+ tempNode = node. next
30
+ }
31
+
32
+ // 2. 각각 next 설정을 snail하게 만듦
33
+ for index in 0 ..< nodeList. count >> 1 {
34
+ nodeList [ nodeList. count - index - 1 ] . next = nodeList [ index] . next === nodeList [ nodeList. count - index - 1 ] ? nil : nodeList [ index] . next
35
+ nodeList [ index] . next = nodeList [ nodeList. count - index - 1 ]
36
+ }
37
+
38
+ // 추가. 만약 노드가 홀수라면 가운데 노드의 next를 nil로 설정
39
+ if nodeList. count & 1 == 1 {
40
+ nodeList [ nodeList. count >> 1 ] . next = nil
41
+ }
42
+ }
43
+ }
You can’t perform that action at this time.
0 commit comments