mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-23 17:01:28 -04:00
fix few details, stacks
This commit is contained in:
parent
578a4f28da
commit
415e9c02e2
18 changed files with 301 additions and 748 deletions
|
@ -1,52 +1,73 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
#!/usr/bin/python
|
||||
|
||||
class Node:
|
||||
def __init__(self, value=None):
|
||||
self.value = value
|
||||
self.next = None
|
||||
__author__ = "Mari Wahl"
|
||||
__email__ = "marina.w4hl@gmail.com"
|
||||
|
||||
class StackwithNodes:
|
||||
''' Define a Stack with nodes'''
|
||||
|
||||
""" A stack made of linked list"""
|
||||
|
||||
|
||||
|
||||
class Node(object):
|
||||
def __init__(self, value=None, pointer=None):
|
||||
self.value = value
|
||||
self.pointer = pointer
|
||||
|
||||
|
||||
class Stack(object):
|
||||
def __init__(self):
|
||||
self.top = None
|
||||
self.head = None
|
||||
|
||||
def isEmpty(self):
|
||||
return bool(self.top)
|
||||
return not bool(self.head)
|
||||
|
||||
def push(self, item):
|
||||
self.head = Node(item, self.head)
|
||||
|
||||
|
||||
def pop(self):
|
||||
node = self.top
|
||||
self.top = node.next
|
||||
return node.value
|
||||
if self.head:
|
||||
node = self.head
|
||||
self.head = node.pointer
|
||||
return node.value
|
||||
else:
|
||||
print('Stack is empty.')
|
||||
|
||||
def push(self, value):
|
||||
node = Node(value)
|
||||
node.next = self.top
|
||||
self.top = node
|
||||
|
||||
def size(self):
|
||||
node = self.top
|
||||
if node not None: num_nodes = 1
|
||||
else: return 0
|
||||
while node.next:
|
||||
num_nodes += 1
|
||||
node = node.next
|
||||
return num_nodes
|
||||
|
||||
def peek(self):
|
||||
return self.top.value
|
||||
|
||||
|
||||
def main():
|
||||
stack = StackwithNodes()
|
||||
stack.push(1)
|
||||
stack.push(2)
|
||||
stack.push(3)
|
||||
print(stack.size())
|
||||
print(stack.peek())
|
||||
print(stack.pop())
|
||||
print(stack.peek())
|
||||
if self.head:
|
||||
return self.head.value
|
||||
else:
|
||||
print('Stack is empty.')
|
||||
|
||||
|
||||
def size(self):
|
||||
node = self.head
|
||||
count = 0
|
||||
while node:
|
||||
count +=1
|
||||
node = node.pointer
|
||||
return count
|
||||
|
||||
|
||||
def _printList(self):
|
||||
node = self.head
|
||||
while node:
|
||||
print(node.value)
|
||||
node = node.pointer
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
stack = Stack()
|
||||
print("Is the stack empty? ", stack.isEmpty())
|
||||
print("Adding 0 to 10 in the stack...")
|
||||
for i in range(10):
|
||||
stack.push(i)
|
||||
stack._printList()
|
||||
print("Stack size: ", stack.size())
|
||||
print("Stack peek : ", stack.peek())
|
||||
print("Pop...", stack.pop())
|
||||
print("Stack peek: ", stack.peek())
|
||||
print("Is the stack empty? ", stack.isEmpty())
|
||||
stack._printList()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue