Its very similar
to the addition in a dynamic linked
list. The only difference is that
here you'll add the new element only at the end of the list, which means
addition can happen only from the TOP. Since a dynamic list is used for the stack,
the Stack is also dynamic, means it has no prior upper limit set. So, we
don't have to check for the Overflow condition at all !
 |
In Step [1] we create the new
element to be PUSHed to the Stack.
In Step [2] the TOP most element is made to point to our newly
created element.
In Step [3] the TOP is moved and made to point to the last
element in the stack, which is our newly added element. |
Algorithm:-
Step-1: If the Stack is empty go to step-2 or else go to step-3
Step-2: Create the new element and make your "stack" and "top" pointers point to it and quit.
Step-3: Create the new element and make the last (top most)
element of the stack to point to it
Step-4: Make that new element your TOP most element by making the
"top" pointer point to it.
C implementation:-
struct node
{
int nodeval;
struct node *next;
}
struct node *stack = NULL; /*stack is
initially empty*/
struct node *top = stack;
main()
{
..
..
push(newvalue);
..
push(newvalue);
..
}
push(int new)
{
if(stack == NULL) /*step-1*/
{
newnode = (struct node *)
malloc(sizeof(node)); /*step-2*/
newnode -> nodeval = new;
newnode -> next = NULL;
stack = newnode;
top = stack;
}
else
{
newnode = (struct node *)malloc(sizeof(node));
/*step-3*/
newnode -> nodeval = new;
newnode -> next = NULL;
top ->next = newnode;
top = newnode; /*step-4*/
}
}
Damn simple, no! I think
no more comments are needed for this...
Note:-
Although, the algorithm for the PUSH operation should remain same
irrespective of the implementation techniques but I've deliberately
changed it a bit to make the implementation easier.
Related Operations:
Concept
Array Implementation - Push() and Pop()
Linked List Implementation - Push()
and Pop()
Application of Stacks
|