-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
54 lines (37 loc) · 900 Bytes
/
stack.py
File metadata and controls
54 lines (37 loc) · 900 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
# Stack Implementation Using Singly Linked List
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.next = None
class Stack:
def __init__(self) -> None:
self.top = None
def is_empty(self) -> bool:
if self.top is None:
return True
return False
def push(self, value) -> None:
node = Node(data=value)
node.next = self.top
self.top = node
def pop(self) -> None:
if self.is_empty():
return None
popped_node = self.top
self.top = self.top.next
popped_node.next = None
return popped_node.data
def peek(self) -> int:
if self.is_empty():
return None
return self.top.data
def __repr__(self) -> str:
if self.is_empty():
return None
str_repr = "\n"
curr = self.top
while curr.next is not None:
str_repr += "|" + str(curr.data) + "|\n"
curr = curr.next
str_repr += "|" + str(curr.data) + "|"
return str_repr