Stack.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //
  2. // Stack.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 16/9/14.
  6. // Copyright © 2016年 zoneland. All rights reserved.
  7. //
  8. import Foundation
  9. class Stack<T> {
  10. fileprivate var top: Int
  11. fileprivate var items: [T]
  12. var size:Int
  13. init() {
  14. top = -1
  15. items = [T]()
  16. size = 100
  17. }
  18. init(size:Int) {
  19. top = -1
  20. items = [T]()
  21. self.size = size
  22. }
  23. func push(_ item: T) -> Bool {
  24. if !isFull() {
  25. items.append(item)
  26. top+=1
  27. return true
  28. }
  29. print("Stack is full! Could not pushed.")
  30. return false
  31. }
  32. func pop() -> T? {
  33. if !isEmpty() {
  34. top-=1
  35. return items.removeLast()
  36. }
  37. print("Stack is empty! Could not popped.")
  38. return nil
  39. }
  40. func peek() -> T? {
  41. if !isEmpty() {
  42. return items.last
  43. }
  44. return nil
  45. }
  46. func isEmpty() -> Bool {
  47. return top == -1
  48. }
  49. func isFull() -> Bool {
  50. return top == (size - 1)
  51. }
  52. func count() -> Int {
  53. return (top + 1)
  54. }
  55. func printStack() {
  56. // for var i = items.count-1; i>=0; i-=1 {
  57. // print("| \(items[i]) |")
  58. // }
  59. // print(" ------ ")
  60. // print("\n\n")
  61. }
  62. }