Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created May 12, 2022 16:45
Show Gist options
  • Save derekli66/817f1b3e53553f247d98106c751c85bd to your computer and use it in GitHub Desktop.
Save derekli66/817f1b3e53553f247d98106c751c85bd to your computer and use it in GitHub Desktop.
Stack Implementation
private class ListNode {
var next: ListNode?
var prev: ListNode?
var key: Int = 0
}
class Stack {
private var head: ListNode?
private var tail: ListNode?
private var count: Int = 0
func push(_ key: Int) {
let newNode = ListNode()
newNode.key = key
if tail == nil {
tail = newNode
head = newNode
}
else {
newNode.next = head
head = newNode
}
count += 1
}
func pop() -> Int {
let lastNode = head
head = lastNode?.next
if head == nil {
tail = nil
}
count -= 1
return lastNode?.key ?? 0
}
func peak() -> Int {
return head?.key ?? 0
}
func size() -> Int {
return count
}
func isEmpty() -> Bool {
return size() == 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment