🔁

2022/07/22に公開

## 完成的程式碼

``````func reverse(_ listNode: ListNode?) -> ListNode? {
var previous: ListNode? = nil
var current = listNode
var next: ListNode? = nil

while current != nil {
next = current?.next
current?.next = previous
previous = current
current = next
}

return previous
}
``````

## 邏輯

### 設定必要的 flags 和初始值

``````var previous: ListNode? = nil
var current = listNode
var next: ListNode? = nil
``````

`previous``next` 是在反轉替換過程中用來暫存節點的 flags

### Routine

``````while current != nil {
next = current?.next
current?.next = previous
previous = current
current = next
}
``````

#### 初始狀態

``````C
1 -> 2 -> 3 -> 4
``````

#### 第一 routine

``````// next = current?.next

C    N
1 -> 2 -> 3 -> 4
``````

``````// current?.next = previous

C    N
1    2 -> 3 -> 4
|
+--> nil
P
``````

``````// previous = current

P
C    N
1    2 -> 3 -> 4
|
+--> nil
``````

current 換到 next 的位置準備下一次的替換

``````// current = next

C
P    N
1    2 -> 3 -> 4
|
+--> nil
``````

### 結束 Routines

``````return previous
``````

## ListNode 的資料結構

• `value` 用來存值
• `next` 用來指向下一個節點

``````class ListNode {
var value: Int
var next: ListNode?

init() {
self.value = 0
self.next = nil
}

init(_ value: Int) {
self.value = value
self.next = nil
}

init(_ value: Int, _ next: ListNode?) {
self.value = value
self.next = next
}

// MARK: - Helper Method

var array: [Int] {
var result = [Int]()
var current: ListNode? = self
while current != nil {
result.append(dummy!.value)
current = current?.next
}
return result
}
}
``````

ログインするとコメントできます