forked from AllAlgorithms/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
56 lines (42 loc) · 938 Bytes
/
Copy pathstack.py
File metadata and controls
56 lines (42 loc) · 938 Bytes
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
44
45
46
47
48
49
50
51
52
53
54
55
56
from node import Node
class Stack:
def __init__(self):
self.head = None
def __str__(self):
node = self.head
list = []
while node:
list.append(node.get_item())
node = node.get_next()
return str(list)
def is_empty(self):
return not self.head
def push(self, item):
if not self.head:
self.head = Node(item)
else:
self.head = Node(item,self.head)
def pop(self):
if not self.head:
raise EmptyStackException('Cannot pop from a empty stack')
else:
item = self.head.get_item()
if self.head.get_next():
self.head = self.head.get_next()
else:
self.head = None
return item
def peek(self):
if not self.head:
raise EmptyStackException('Cannot peek from an empty stack')
else:
return self.head.get_item()
def size(self):
count = 0
node = self.head
while node:
count += 1
node = node.get_next()
return count
class EmptyStackException(Exception):
pass