Define Stack ADT with an Implementation of stack in python | Implementation of stack in python using list | define stack ADT |

 Define Stack ADT with an Implementation of stack in python | Implementation of stack in python using list | define stack ADT |


Define Stack ADT –


Stack is a linear data structure where the element can be inserted and deleted at one end Top.  Push and pop operation on stack are done in Last In First Out (LIFO)  manner. if stack is empty that means  stack containing no items.


Define Stack ADT with an Implementation 




Operation performed on Stack -


1. Stack(): Creates a new empty stack.


2. isEmpty(): Returns a boolean value indicating if the stack is 

                            empty.

3. length() /Size(): Returns the number of items in the stack.


4.     pop(): Removes and returns the top item of the stack.


5.    peek() / top(): Returns a reference to the item on top of a non-empty stack without removing it. Peeking operation cannot be done on an empty stack.


6.    push(item): Adds the given item to the top of the stack.



For example if  Stack is class name of class and s is instance of a class has been created and starts out empty table shows the result of a sequence of stack operations.






Implementing The Stack -

The stack ADT can be implemented using  of Python  List.


class Stack:
    def __init__(self):
        self.items = []
    def IsEmpty(self):
         return self.items == []
    def push(self,item):
        self.items.append(item) 
        print(item)

    def pop(self):
        return self.items.pop()
    def top(self):
        return self.items[len(self.items)-1]
    def size(self):
        return len(self.items)
s=Stack()
s.push(2)
s.push(3)
s.push(4)
print(s.items)
print("pop-",s.pop())
print("size-",s.size())
print(s.top())
print(s.IsEmpty())

Output



 
2
3
4
[2, 3, 4]
pop- 4
size- 2
3
False




















Post a Comment

Post a Comment (0)

Previous Post Next Post