refactor: use internal method and remove toArray() method

pull/240/head
nuomi1 2 years ago
parent 99f1494939
commit ac7d26c131
No known key found for this signature in database
GPG Key ID: E410D5FF602FBF25

@ -29,8 +29,9 @@ class ArrayStack {
} }
/* */ /* */
@discardableResult
func pop() -> Int { func pop() -> Int {
if stack.isEmpty { if isEmpty() {
fatalError("栈为空") fatalError("栈为空")
} }
return stack.removeLast() return stack.removeLast()
@ -38,7 +39,7 @@ class ArrayStack {
/* 访 */ /* 访 */
func peek() -> Int { func peek() -> Int {
if stack.isEmpty { if isEmpty() {
fatalError("栈为空") fatalError("栈为空")
} }
return stack.last! return stack.last!

@ -20,7 +20,7 @@ class LinkedListStack {
/* */ /* */
func isEmpty() -> Bool { func isEmpty() -> Bool {
_size == 0 size() == 0
} }
/* */ /* */
@ -32,6 +32,7 @@ class LinkedListStack {
} }
/* */ /* */
@discardableResult
func pop() -> Int { func pop() -> Int {
let num = peek() let num = peek()
_peek = _peek?.next _peek = _peek?.next
@ -41,7 +42,7 @@ class LinkedListStack {
/* 访 */ /* 访 */
func peek() -> Int { func peek() -> Int {
if _size == 0 { if isEmpty() {
fatalError("栈为空") fatalError("栈为空")
} }
return _peek!.val return _peek!.val

@ -641,7 +641,7 @@ comments: true
/* 判断栈是否为空 */ /* 判断栈是否为空 */
func isEmpty() -> Bool { func isEmpty() -> Bool {
_size == 0 size() == 0
} }
/* 入栈 */ /* 入栈 */
@ -653,6 +653,7 @@ comments: true
} }
/* 出栈 */ /* 出栈 */
@discardableResult
func pop() -> Int { func pop() -> Int {
let num = peek() let num = peek()
_peek = _peek?.next _peek = _peek?.next
@ -662,22 +663,11 @@ comments: true
/* 访问栈顶元素 */ /* 访问栈顶元素 */
func peek() -> Int { func peek() -> Int {
if _size == 0 { if isEmpty() {
fatalError("栈为空") fatalError("栈为空")
} }
return _peek!.val 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
}
} }
``` ```
@ -994,8 +984,9 @@ comments: true
} }
/* 出栈 */ /* 出栈 */
@discardableResult
func pop() -> Int { func pop() -> Int {
if stack.isEmpty { if isEmpty() {
fatalError("栈为空") fatalError("栈为空")
} }
return stack.removeLast() return stack.removeLast()
@ -1003,16 +994,11 @@ comments: true
/* 访问栈顶元素 */ /* 访问栈顶元素 */
func peek() -> Int { func peek() -> Int {
if stack.isEmpty { if isEmpty() {
fatalError("栈为空") fatalError("栈为空")
} }
return stack.last! return stack.last!
} }
/* 将 List 转化为 Array 并返回 */
func toArray() -> [Int] {
stack
}
} }
``` ```

Loading…
Cancel
Save