Created
March 26, 2018 20:11
-
-
Save m1k3yfoo/2dd76a86de5521a64f225797c0e3bdfb to your computer and use it in GitHub Desktop.
[Python Stack]
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
# Using lists as stacks | |
stack = [3, 4, 5] | |
stack.append(6) ## Same as push | |
stack.pop() | |
## Custom implementation of stack using LinkedList (See LinkedList) | |
class Element(object): | |
def __init__(self, value): | |
self.value = value | |
self.next = None | |
class LinkedList(object): | |
def __init__(self, head=None): | |
self.head = head | |
def append(self, new_element): | |
current = self.head | |
if self.head: | |
while current.next: | |
current = current.next | |
current.next = new_element | |
else: | |
self.head = new_element | |
def insert_first(self, new_element): | |
"Insert new element as the head of the LinkedList" | |
new_element.next = self.head | |
self.head = new_element | |
def delete_first(self): | |
"Delete the first (head) element in the LinkedList as return it" | |
deleted = self.head | |
if self.head: | |
self.head = self.head.next | |
deleted.next = None | |
return deleted | |
class Stack(object): | |
def __init__(self,top=None): | |
self.ll = LinkedList(top) | |
def push(self, new_element): | |
"Push (add) a new element onto the top of the stack" | |
self.ll.insert_first(new_element) | |
def pop(self): | |
"Pop (remove) the first element off the top of the stack and return it" | |
return self.ll.delete_first() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment