Feb. 6, 2022, 7:13 p.m.
Stack is a linear data structure and it follows last in first out principle(LIFO).
Which means the last inserted item is popped out first and then the other and so on.
You will get a clear picture of what stack exactly is by looking at the picture present with this article. Here 3 boxes are stacked up the upper one will be the first one to be popped out in order to reach the last box which is first inserted in this stack.
Stack is a linear data structure and it follows last in first out principle(LIFO).
Which means the last inserted item is popped out first and then the other and so on.
You will get a clear picture of what stack exactly is by looking at the picture present with this article. Here 3 boxes are stacked up the upper one will be the first one to be popped out in order to reach the last box which is first inserted in this stack.
Here is an Algorithm for Stack.
In this algorithm there are 3 methods one is push that is for inserting the item another is pop that is to delete the item from the stack and the third one print_stack is for displaying the items in the stack.
class Node:
def __init__(self,value):
self.value=value
self.next=None
class stack:
def __init__(self,value):
new_node=Node(value)
self.top=new_node
self.height=1
def print_stack(self):
temp=self.top
while temp:
print(temp.value)
temp=temp.next
print(self.height)
def push(self,value):
new_node=Node(value)
if self.height==0:
self.top=new_node
else:
new_node.next=self.top
self.top=new_node
self.height+=1
def pop(self):
if self.top is None:
return False
else:
temp=self.top
self.top=temp.next
self.height-=1
mystack=stack(2)
mystack.push(6)
mystack.push(8)
mystack.pop()
mystack.print_stack()