Created
May 12, 2022 16:45
-
-
Save derekli66/817f1b3e53553f247d98106c751c85bd to your computer and use it in GitHub Desktop.
Stack Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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