Last active
December 20, 2019 03:17
-
-
Save sleebapaul/67e2e8550b543532541d828c962e202f to your computer and use it in GitHub Desktop.
Implementation of Stack using Linked List
This file contains 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
class Node(object): | |
""" | |
Fundamental building block of a linked list | |
A node consists of a value and the next node location pointer | |
""" | |
def __init__(self, value): | |
self.val = value | |
self.next = None | |
class MyStack(object): | |
""" | |
Stack implementation using LinkedList | |
Stack is a LIFO queue | |
""" | |
def __init__(self): | |
""" | |
Initialize stack | |
""" | |
self.head = None | |
def pushItem(self, val): | |
""" | |
Push new value to stack | |
(Push the new value to the front of linked list - O(1)) | |
""" | |
newItem = Node(val) | |
newItem.next = self.head | |
self.head = newItem | |
def popItem(self): | |
""" | |
Pop the top value of the stack | |
(Pop the new value from the front of linked list - O(1)) | |
""" | |
try: | |
self.head = self.head.next | |
except AttributeError as error: | |
self.head = None | |
def peekItem(self): | |
""" | |
Peek the top value of stack | |
(Peek the top value the front of linked list - O(1)) | |
""" | |
try: | |
return self.head.val | |
except AttributeError as error: | |
return None | |
def isEmpty(self): | |
""" | |
Check is stack is empty | |
(Check if head of linked list is none - O(1)) | |
""" | |
return self.head is None | |
# if __name__ == "__main__": | |
# myStack = MyStack() | |
# print("Top value of stack: ", myStack.peekItem()) | |
# myStack.pushItem(8) | |
# myStack.pushItem(7) | |
# print("Top value of stack: ", myStack.peekItem()) | |
# myStack.popItem() | |
# print("Top value of stack: ", myStack.peekItem()) | |
# myStack.popItem() | |
# myStack.popItem() | |
# myStack.popItem() | |
# print("Is empty: ", myStack.isEmpty()) | |
# print("Top value of stack: ", myStack.peekItem()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment