-
Notifications
You must be signed in to change notification settings - Fork 8
/
stack_dsa_tutorial.py
60 lines (52 loc) · 1.43 KB
/
stack_dsa_tutorial.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
## 08.05.2024
# Creating stack using linkedlist
"""
Stack operations:
creating node - [Done]
creating stack - [Done]
push - To insert an element to last - [Done]
pop - To remove/out from the last (LIFO) concept - [Done]
peak - To retreive data of the top - [Done]
is_empty - to check the stack is empty - [Done]
length - to get the size of the stack - [Done]
traverse - to print the elements in the stack - [Done]
"""
class Node:
def __init__(self, value):
self.data = value
self.next = None
class Stack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top == None
def push(self, value):
new_node = Node(value)
new_node.next = self.top
self.top = new_node
def pop(self):
if self.is_empty():
return "Stack is empty!!"
data = self.top.data
self.top = self.top.next
return data
def peak(self):
if self.is_empty():
return "Stack is empty!!"
return self.top.data
def __len__(self):
size = 0
if self.is_empty():
return size
curr = self.top
while curr != None:
size+=1
curr = curr.next
return size
def __str__(self):
result = ""
curr = self.top
while curr != None:
result = result+str(curr.data)+", "
curr = curr.next
return "[ "+result[:-2]+" ]"