forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWhiteHyun.swift
43 lines (38 loc) ยท 1.29 KB
/
WhiteHyun.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//
// 143. Reorder List
// https://leetcode.com/problems/reorder-list/description/
// Dale-Study
//
// Created by WhiteHyun on 2024/06/10.
//
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func reorderList(_ head: ListNode?) {
guard head?.next != nil else { return }
var nodeList: [ListNode] = []
var tempNode = head
// 1. ๊ฐ ๋
ธ๋๋ฅผ ์ ํ์ผ๋ก ํ์ธํ๋ฉฐ ๋ฆฌ์คํธ์ ์ถ๊ฐ
while let node = tempNode {
nodeList.append(node)
tempNode = node.next
}
// 2. ๊ฐ๊ฐ next ์ค์ ์ snailํ๊ฒ ๋ง๋ฆ
for index in 0 ..< nodeList.count >> 1 {
nodeList[nodeList.count - index - 1].next = nodeList[index].next === nodeList[nodeList.count - index - 1] ? nil : nodeList[index].next
nodeList[index].next = nodeList[nodeList.count - index - 1]
}
//ใ์ถ๊ฐ. ๋ง์ฝ ๋
ธ๋๊ฐ ํ์๋ผ๋ฉด ๊ฐ์ด๋ฐ ๋
ธ๋์ next๋ฅผ nil๋ก ์ค์
if nodeList.count & 1 == 1 {
nodeList[nodeList.count >> 1].next = nil
}
}
}