Skip to content

Commit 2cb1627

Browse files
authored
Update stack.py
linkedlist stack
1 parent 5f99866 commit 2cb1627

File tree

1 file changed

+59
-1
lines changed
  • Data Structures and Algorithms/stack

1 file changed

+59
-1
lines changed

Data Structures and Algorithms/stack/stack.py

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
class stack:
2-
2+
33
def __init__(self):
44
self.items=input()
55
print(self.items.lstrip)
@@ -21,6 +21,64 @@ def print_stack(self):
2121
stack1.pop() #allows one to remove items to the stack
2222
stack1.print_stack()
2323

24+
# stack implemetation using linkedlist
25+
26+
# Create a class for Node that represents an individual element of the linked list
27+
class Node:
28+
29+
def __init__(self, data):
30+
self.data = data
31+
self.next = None
32+
33+
34+
class StackLinked:
35+
def __init__(self):
36+
self.start = None
37+
38+
# Method to add a new element to the top of the stack
39+
def push(self, data):
40+
newNode = Node(data)
41+
42+
# If the stack is empty, make the new node the first element
43+
if(self.start == None):
44+
self.start = newNode
45+
else:
46+
47+
# If the stack already has elements, add the new node to the top of the stack
48+
newNode.next = self.start
49+
self.start = newNode
50+
51+
# Method to remove the top element from the stack
52+
def pop(self):
53+
if self.start is not None:
54+
self.start = self.start.next
55+
56+
# Method to get the top element of the stack
57+
def top(self):
58+
return self.start
59+
60+
# Method to check if the stack is empty
61+
def isEmpty(self):
62+
return self.start == None
63+
64+
# Method to check if the stack is full
65+
def isFull(self):
66+
newNode = Node(None)
67+
return newNode == None
68+
69+
70+
S = StackLinked()
71+
72+
S.push(45)
73+
S.push(90)
74+
S.push(12)
75+
S.pop()
76+
print(S.isEmpty())
77+
print(S.isFull())
78+
top_element = S.top()
79+
print(top_element.data)
80+
81+
2482

2583

2684

0 commit comments

Comments
 (0)