Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

Stack

 What is Stack Data Structure?



In computer science, a stack is a linear data structure that allows data to be added and removed in a specific order. It is based on the principle of Last-In-First-Out (LIFO), which means that the last element added to the stack is the first one to be removed.


A stack can be visualized as a collection of items that are piled up on top of each other. The item that is added last is placed on top of the stack, while the item that is added first is at the bottom of the stack.


The main operations that can be performed on a stack are:


Push: Adds an item to the top of the stack.

Pop: Removes the item from the top of the stack.

Peek: Returns the item at the top of the stack without removing it.

IsEmpty: Returns true if the stack is empty, false otherwise.





Stacks are commonly used in programming for various applications, such as managing function calls, expression evaluation, undo/redo functionality, and more.


Implementation of Stack in Python:

CODE:

class Stack:

    def __init__(self):

        self.items=[]

 

    def isEmpty(self):

        return self.items==[]

 

    def push(self,item):

        self.items.append(item)

 

    def pop(self):

        return self.items.pop()

    

    def peek(self):

        return self.items[len(self.items)-1]

 

    def size(self):

        return self.items

 

    def getelements(self):

        return self.items

 

s= Stack()

n= int(input("How many elements youn want?"))

for i in range(n):

    elt=input("Enter element:")

    s.push(elt)

 

print(s.getelements())

print(s.isEmpty())

print(s.pop())

print(s.size())

print(s.peek())

OUTPUT:




Stack Stack Reviewed by Asst. Prof. Sunita Rai on April 09, 2023 Rating: 5

No comments:

Powered by Blogger.