25: Implement a stack using an array or linked list.
⏳⌚ 00:00:00

Question:-

Implement a stack using an array or linked list.
Example 1:
Input: according to question: Output:
44 -> 33 -> 22 -> 11
Top element is 44
22 -> 11
Top element is 22

Steps to solve:-

1. Node class:- br The code defines a Node class, which represents a single element in the linked list. Each Node has two attributes: data (to store the value of the element) and link (a pointer to the next Node in the list). The Node class has a constructor that initializes these attributes.
2. stack calss:-
The code also defines a Stack class, which represents the stack data structure. It has a private member variable top, which is a pointer to the top element in the stack. Initially, top is set to NULL to indicate an empty stack.
3. Operations in stack:- The Stack class provides several methods to manipulate the stack:
**push(int data): This method is used to push an element onto the stack. It creates a new Node with the given data, checks for stack overflow, and inserts the new node at the top of the stack.
**pop(): This method removes the top element from the stack. It checks for stack underflow and deletes the top node.
**isEmpty(): This method checks if the stack is empty by examining whether top is NULL.
**peek(): This method returns the value of the top element in the stack without removing it. It checks if the stack is empty and returns the top element's data if it's not empty.
**display(): This method is used to print all the elements of the stack. It traverses the linked list, starting from top, and prints the data values of each element.
4. main function:-
In the main function, an instance of the Stack class is created as s.
Several elements (11, 22, 33, 44) are pushed onto the stack using the push method.
The elements in the stack are displayed using the display method, and the top element is printed using the peek method.
Two elements are popped from the stack using the pop method.
The remaining elements in the stack are displayed again, and the top element is printed.

solution->

View Code 1
Time Complexity = O(n)
Space Complexity = O(n)