-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
44 lines (36 loc) · 924 Bytes
/
stack.py
File metadata and controls
44 lines (36 loc) · 924 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
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top = None
self._size = 0
def push(self, item):
new_node = Node(item)
new_node.next = self.top
self.top = new_node
self._size +=1
def pop(self):
if self.top is None:
raise IndexError("Empty stack")
popped_node = self.top
self.top = popped_node.next
self._size -=1
return popped_node.value
def peek(self):
if self.top is None:
raise IndexError("Empty stack")
return self.top.value
def size(self):
return self._size
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # 3
print(stack.peek()) # 2
print(stack.size()) # 2
print(stack.pop()) # 2
print(stack.pop()) # 1
print(stack.pop()) # Error