A stack is a collection of objects that are inserted and removed using Last in First out Principle(LIFO). User can insert elements into the stack, and can only access or remove the recently inserted object on top of the stack. The main advantage of using LinkedList over array for implementing stack is the dynamic allocation of data whereas in the array, the size of the stack is restricted and there is a chance of stack overflow error when the size of the stack is exceeded the maximum size.
1. push() : Insert the element into Stack and assign the top pointer to the element.
2. pop() : Return top element from the Stack and move the top pointer to the
second element of the Stack.
3. top() : Return the top element.
4. size() : Return the Size of the Stack.
5. isEmpty() : Return True if Stack is Empty else return False.
6. printstack() : Print all elements of the stack.
Below is the implementation of the above-mentioned stack operations using Doubly LinkedList in Python:
Stack operations using Doubly LinkedList stack elements are: 7->6->5->4-> Top element is 7 Size of the stack is 4 stack elements are: 5->4-> stack is empty: False
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course