Skip to content

Commit 0b8acd6

Browse files
authored
stack using linked list
stack using linked list
1 parent b5cec85 commit 0b8acd6

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Python/stack using linked list.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
class Node:
2+
def __init__(self,value=None):
3+
self.value = value
4+
self.next=next
5+
6+
class LinkedList:
7+
def __init__(self):
8+
self.head=None
9+
10+
def __iter__(self):
11+
curNode=self.head
12+
while curNode:
13+
yield curNode
14+
curNode=curNode.next
15+
16+
class Stack:
17+
def __init__(self):
18+
self.LinkedList=LinkedList()
19+
20+
def __str__(self):
21+
values=[str(x.value) for x in self.LinkedList]
22+
return '\n'.join(values)
23+
24+
def isEmpty(self):
25+
if self.LinkedList.head == None:
26+
return True
27+
else:
28+
return False
29+
30+
def push(self,value):
31+
node=Node(value)
32+
node.next=self.LinkedList.head
33+
self.LinkedList.head = node
34+
35+
#pop
36+
def pop(self):
37+
if self.isEmpty():
38+
print("there is no element in the stack")
39+
else:
40+
nodeValue=self.LinkedList.head.value
41+
self.LinkedList.head=self.LinkedList.head.next
42+
return nodeValue
43+
44+
# peek
45+
def peek(self):
46+
if self.isEmpty():
47+
print("there is no element in the stack")
48+
else:
49+
nodeValue=self.LinkedList.head.value
50+
return nodeValue
51+
52+
53+
54+
# delete entire stack
55+
def delete(self):
56+
self.list=None
57+
58+
59+
customStack = Stack()
60+
customStack.push(1)
61+
customStack.push(2)
62+
customStack.push(3)
63+
print(customStack)
64+
65+
print("\n")
66+
customStack.pop()
67+
print(customStack)
68+
69+
print("\n")
70+
71+
print(customStack.peek())
72+
print(customStack)

0 commit comments

Comments
 (0)