-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.py
42 lines (29 loc) · 829 Bytes
/
stack.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
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
self.size = 0
def push(self, data):
node = Node(data)
if not self.top:
self.top = node
else:
# make previous top element to next of new top
node.next = self.top
self.top = node
self.size += 1
def pop(self):
if self.top:
# remove current top from stack and return
current_item = self.top
self.top = self.top.next
self.size -= 1
return current_item.data
return None
def peek(self):
if self.top:
return self.top.data
return None