This commit is contained in:
krahets
2023-02-08 20:30:14 +08:00
parent 7156a5f832
commit 30ed83e5b1
10 changed files with 130 additions and 49 deletions

View File

@@ -751,19 +751,19 @@ comments: true
private var front: ListNode? // 头结点
private var rear: ListNode? // 尾结点
private var _size = 0
init() {}
/* 获取队列的长度 */
func size() -> Int {
_size
}
/* 判断队列是否为空 */
func isEmpty() -> Bool {
size() == 0
}
/* 入队 */
func push(num: Int) {
// 尾结点后添加 num
@@ -780,7 +780,7 @@ comments: true
}
_size += 1
}
/* 出队 */
@discardableResult
func poll() -> Int {
@@ -790,7 +790,7 @@ comments: true
_size -= 1
return num
}
/* 访问队首元素 */
func peek() -> Int {
if isEmpty() {
@@ -798,6 +798,17 @@ comments: true
}
return front!.val
}
/* 将链表转化为 Array 并返回 */
func toArray() -> [Int] {
var node = front
var res = Array(repeating: 0, count: size())
for i in res.indices {
res[i] = node!.val
node = node?.next
}
return res
}
}
```
@@ -1380,6 +1391,16 @@ comments: true
}
return nums[front]
}
/* 返回数组 */
func toArray() -> [Int] {
// 仅转换有效长度范围内的列表元素
var res = Array(repeating: 0, count: queSize)
for (i, j) in sequence(first: (0, front), next: { $0 < self.queSize - 1 ? ($0 + 1, $1 + 1) : nil }) {
res[i] = nums[j % capacity()]
}
return res
}
}
```

View File

@@ -687,19 +687,19 @@ comments: true
class LinkedListStack {
private var _peek: ListNode? // 将头结点作为栈顶
private var _size = 0 // 栈的长度
init() {}
/* 获取栈的长度 */
func size() -> Int {
_size
}
/* 判断栈是否为空 */
func isEmpty() -> Bool {
size() == 0
}
/* 入栈 */
func push(num: Int) {
let node = ListNode(x: num)
@@ -707,7 +707,7 @@ comments: true
_peek = node
_size += 1
}
/* 出栈 */
@discardableResult
func pop() -> Int {
@@ -716,7 +716,7 @@ comments: true
_size -= 1
return num
}
/* 访问栈顶元素 */
func peek() -> Int {
if isEmpty() {
@@ -724,6 +724,17 @@ comments: true
}
return _peek!.val
}
/* 将 List 转化为 Array 并返回 */
func toArray() -> [Int] {
var node = _peek
var res = Array(repeating: 0, count: _size)
for i in sequence(first: res.count - 1, next: { $0 >= 0 + 1 ? $0 - 1 : nil }) {
res[i] = node!.val
node = node?.next
}
return res
}
}
```
@@ -1076,27 +1087,27 @@ comments: true
/* 基于数组实现的栈 */
class ArrayStack {
private var stack: [Int]
init() {
// 初始化列表(动态数组)
stack = []
}
/* 获取栈的长度 */
func size() -> Int {
stack.count
}
/* 判断栈是否为空 */
func isEmpty() -> Bool {
stack.isEmpty
}
/* 入栈 */
func push(num: Int) {
stack.append(num)
}
/* 出栈 */
@discardableResult
func pop() -> Int {
@@ -1105,7 +1116,7 @@ comments: true
}
return stack.removeLast()
}
/* 访问栈顶元素 */
func peek() -> Int {
if isEmpty() {
@@ -1113,6 +1124,11 @@ comments: true
}
return stack.last!
}
/* 将 List 转化为 Array 并返回 */
func toArray() -> [Int] {
stack
}
}
```