8000 Add files via upload · ospluscode/Stack-Queue@cbf8e7c · GitHub
[go: up one dir, main page]

Skip to content

Commit cbf8e7c

Browse files
authored
Add files via upload
Stack implementation using Linked List
1 parent 8c2ddba commit cbf8e7c

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

stackLinkedList.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Stack implementation using LinkedList
2+
# Simply, the idea is to insert a node to the head of LinkedList
3+
# each time we push an element to the Stack
4+
# All Time and Space complexity O(1)
5+
6+
class Node:
7+
def __init__(self, value = None):
8+
self.value = value
9+
self.next = None
10+
11+
12+
class LinkedList:
13+
def __init__(self):
14+
self.head = None
15+
16+
def __iter__(self):
17+
current_node = self.head
18+
while current_node:
19+
yield current_node
20+
current_node = current_node.next
21+
22+
23+
class Stack:
24+
def __init__(self):
25+
self.linked_list = LinkedList()
26+
27+
def __str__(self):
28+
values = [str(v.value) for v in self.linked_list]
29+
return '\n'.join(values)
30+
31+
32+
def isEmpty(self):
33+
if self.linked_list.head == None:
34+
return True
35+
else:
36+
return False
37+
38+
39+
# add node to the head/first
40+
def push(self, value):
41+
node = Node(value)
42+
node.next = self.linked_list.head
43+
self.linked_list.head = node
44+
45+
46+
def peek(self):
47+
if self.isEmpty():
48+
return "Stack is empty"
49+
else:
50+
node_value = self.linked_list.head.value
51+
return node_value
52+
53+
54+
# get the head/first node
55+
def pop(self):
56+
if self.isEmpty():
57+
return "Stack is empty"
58+
else:
59+
node_value = self.linked_list.head.value
60+
self.linked_list.head = self.linked_list.head.next
61+
return node_value
62+
63+
64+
def delete(self):
65+
self.linked_list.head = None

0 commit comments

Comments
 (0)
0