-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStacks.py
43 lines (34 loc) · 1006 Bytes
/
Stacks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Implementation of Stacks in Python using Linked List
# Provides better performance for large stacks
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, item):
new_node = Node(item)
new_node.next = self.top
self.top = new_node
def pop(self):
if not self.is_empty():
item = self.top.value
self.top = self.top.next
return item
else:
raise Exception("pop from empty stack")
def peek(self):
if not self.is_empty():
return self.top.value
else:
raise Exception("pop from empty stack")
def size(self):
count = 0
curr = self.top
while curr:
count += 1
curr = curr.next
return count
def is_empty(self):
return True if self.size() == 0 else False