From ac7d26c131c834d10fe951cd3615264a97a5f4fc Mon Sep 17 00:00:00 2001 From: nuomi1 Date: Wed, 11 Jan 2023 23:54:04 +0800 Subject: [PATCH] refactor: use internal method and remove toArray() method --- .../chapter_stack_and_queue/array_stack.swift | 5 ++-- .../linkedlist_stack.swift | 5 ++-- docs/chapter_stack_and_queue/stack.md | 26 +++++-------------- 3 files changed, 12 insertions(+), 24 deletions(-) diff --git a/codes/swift/chapter_stack_and_queue/array_stack.swift b/codes/swift/chapter_stack_and_queue/array_stack.swift index faeeaa173..144ebec95 100644 --- a/codes/swift/chapter_stack_and_queue/array_stack.swift +++ b/codes/swift/chapter_stack_and_queue/array_stack.swift @@ -29,8 +29,9 @@ class ArrayStack { } /* 出栈 */ + @discardableResult func pop() -> Int { - if stack.isEmpty { + if isEmpty() { fatalError("栈为空") } return stack.removeLast() @@ -38,7 +39,7 @@ class ArrayStack { /* 访问栈顶元素 */ func peek() -> Int { - if stack.isEmpty { + if isEmpty() { fatalError("栈为空") } return stack.last! diff --git a/codes/swift/chapter_stack_and_queue/linkedlist_stack.swift b/codes/swift/chapter_stack_and_queue/linkedlist_stack.swift index 9d3c98b01..97f7dabcc 100644 --- a/codes/swift/chapter_stack_and_queue/linkedlist_stack.swift +++ b/codes/swift/chapter_stack_and_queue/linkedlist_stack.swift @@ -20,7 +20,7 @@ class LinkedListStack { /* 判断栈是否为空 */ func isEmpty() -> Bool { - _size == 0 + size() == 0 } /* 入栈 */ @@ -32,6 +32,7 @@ class LinkedListStack { } /* 出栈 */ + @discardableResult func pop() -> Int { let num = peek() _peek = _peek?.next @@ -41,7 +42,7 @@ class LinkedListStack { /* 访问栈顶元素 */ func peek() -> Int { - if _size == 0 { + if isEmpty() { fatalError("栈为空") } return _peek!.val diff --git a/docs/chapter_stack_and_queue/stack.md b/docs/chapter_stack_and_queue/stack.md index 04825695c..7ff3f15bf 100644 --- a/docs/chapter_stack_and_queue/stack.md +++ b/docs/chapter_stack_and_queue/stack.md @@ -641,7 +641,7 @@ comments: true /* 判断栈是否为空 */ func isEmpty() -> Bool { - _size == 0 + size() == 0 } /* 入栈 */ @@ -653,6 +653,7 @@ comments: true } /* 出栈 */ + @discardableResult func pop() -> Int { let num = peek() _peek = _peek?.next @@ -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 - } } ``` @@ -994,8 +984,9 @@ comments: true } /* 出栈 */ + @discardableResult func pop() -> Int { - if stack.isEmpty { + if isEmpty() { fatalError("栈为空") } return stack.removeLast() @@ -1003,16 +994,11 @@ comments: true /* 访问栈顶元素 */ func peek() -> Int { - if stack.isEmpty { + if isEmpty() { fatalError("栈为空") } return stack.last! } - - /* 将 List 转化为 Array 并返回 */ - func toArray() -> [Int] { - stack - } } ```