Stack Dotx
Stack Dotx
Stack is a linear data structure in which the insertion and deletion operations are performed at only
one end. In a stack, adding and removing of elements are performed at a single position which is
known as "top". That means, a new element is added at top of the stack and an element is removed
from the top of the stack. In stack, the insertion and deletion operations are performed based on
LIFO (Last In First Out) principle.
In a stack, the insertion operation is performed using a function called "push" and deletion
operation is performed using a function called "pop".
In the figure, PUSH and POP operations are performed at a top position in the stack. That means,
both the insertion and deletion operations are performed at one end (i.e., at Top)
Example
If we want to create a stack by inserting 10,45,12,16,35 and 50. Then 10 becomes the bottom-most
element and 50 is the topmost element. The last inserted element 50 is at Top of the stack as shown
in the image below...
Operations on a Stack
The following operations are performed on the stack...
1. Push (To insert an element on to the stack)
2. Pop (To delete an element from the stack)
3. Display (To display elements of the stack)
Stack data structure can be implemented in two ways. They are as follows...
1. Using Array
2. Using Linked List
When a stack is implemented using an array, that stack can organize an only limited number of
elements. When a stack is implemented using a linked list, that stack can organize an unlimited
number of elements.
Before implementing actual operations, first follow the below steps to create an empty stack.
Step 1 - Include all the header files which are used in the program and define a constant
'SIZE' with specific value.
Step 2 - Declare all the functions used in stack implementation.
Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5 - In main method, display menu with list of operations and make suitable function
calls to perform operation selected by the user on the stack.
In linked list implementation of a stack, every new element is inserted as 'top' element. That means
every newly inserted element is pointed by 'top'. Whenever we want to remove an element from the
stack, simply remove the node which is pointed by 'top' by moving 'top' to its previous node in the
list. The next field of the first element must be always NULL.
Example
In the above example, the last inserted node is 99 and the first inserted node is 25. The order of
elements inserted is 25, 32,50 and 99.