Guest User

Untitled

a guest
Oct 18th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. struct Stack<Element> {
  2. var items = [Element]()
  3.  
  4. var count : Int {
  5. return items.count
  6. }
  7.  
  8. mutating func push(_ item: Element) {
  9. items.append(item)
  10. }
  11.  
  12. mutating func pop() -> Element? {
  13. return items.removeLast()
  14. }
  15.  
  16. func peek() -> Element? {
  17. return items.last
  18. }
  19. }
  20.  
  21. struct Queue<Element> {
  22. var inStack = Stack<Element>()
  23. var outStack = Stack<Element>()
  24.  
  25. mutating func enqueue(_ item: Element) {
  26. inStack.push(item)
  27. }
  28.  
  29. mutating func dequeue() -> Element? {
  30. fillOutStack()
  31. return outStack.pop()
  32. }
  33.  
  34. mutating func peek() -> Element? {
  35. fillOutStack()
  36. return outStack.peek()
  37. }
  38.  
  39. private mutating func fillOutStack() {
  40. if outStack.count == 0 {
  41. while inStack.count != 0 {
  42. outStack.push(inStack.pop()!)
  43. }
  44. }
  45. }
  46. }
Add Comment
Please, Sign In to add comment