Skip to content

Commit

Permalink
refactor: use internal method and remove toArray() method
Browse files Browse the repository at this point in the history
  • Loading branch information
nuomi1 committed Jan 11, 2023
1 parent 99f1494 commit ac7d26c
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 24 deletions.
5 changes: 3 additions & 2 deletions codes/swift/chapter_stack_and_queue/array_stack.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,17 @@ class ArrayStack {
}

/* 出栈 */
@discardableResult
func pop() -> Int {
if stack.isEmpty {
if isEmpty() {
fatalError("栈为空")
}
return stack.removeLast()
}

/* 访问栈顶元素 */
func peek() -> Int {
if stack.isEmpty {
if isEmpty() {
fatalError("栈为空")
}
return stack.last!
Expand Down
5 changes: 3 additions & 2 deletions codes/swift/chapter_stack_and_queue/linkedlist_stack.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class LinkedListStack {

/* 判断栈是否为空 */
func isEmpty() -> Bool {
_size == 0
size() == 0
}

/* 入栈 */
Expand All @@ -32,6 +32,7 @@ class LinkedListStack {
}

/* 出栈 */
@discardableResult
func pop() -> Int {
let num = peek()
_peek = _peek?.next
Expand All @@ -41,7 +42,7 @@ class LinkedListStack {

/* 访问栈顶元素 */
func peek() -> Int {
if _size == 0 {
if isEmpty() {
fatalError("栈为空")
}
return _peek!.val
Expand Down
26 changes: 6 additions & 20 deletions docs/chapter_stack_and_queue/stack.md
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ comments: true

/* 判断栈是否为空 */
func isEmpty() -> Bool {
_size == 0
size() == 0
}

/* 入栈 */
Expand All @@ -653,6 +653,7 @@ comments: true
}

/* 出栈 */
@discardableResult
func pop() -> Int {
let num = peek()
_peek = _peek?.next
Expand All @@ -662,22 +663,11 @@ comments: true

/* 访问栈顶元素 */
func peek() -> Int {
if _size == 0 {
if isEmpty() {
fatalError("栈为空")
}
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
}
}
```

Expand Down Expand Up @@ -994,25 +984,21 @@ comments: true
}

/* 出栈 */
@discardableResult
func pop() -> Int {
if stack.isEmpty {
if isEmpty() {
fatalError("栈为空")
}
return stack.removeLast()
}

/* 访问栈顶元素 */
func peek() -> Int {
if stack.isEmpty {
if isEmpty() {
fatalError("栈为空")
}
return stack.last!
}

/* 将 List 转化为 Array 并返回 */
func toArray() -> [Int] {
stack
}
}
```

Expand Down

0 comments on commit ac7d26c

Please sign in to comment.