Representing Stack in C - Data Structure

A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted at one end , called the top of the stack.

Representing Stack in C - Data Structure

The Stack provides for the insertion and deletion of items, so that a stack is a dynamic, constantly changing object.


#define MAXSIZE 100
struct stack {
 int items[MAXSIZE];
 int top;
};

Note: If the value of s-top is 4 there are five elements on the stack i.e s.item[0], s.items[1], s.items[2], s.items[3], s.items[4]
When the stack is popped, the value of the stack is changed to 3 and indicate that there are now 4 elements and the top element is s.item[3].

When the new items is pushed onto the stack, the value of s.top must be increased by 1 i.e s.top becomes 5 and the new item is inserted into s.items[5].

To indicate the stack s to the empty stack we should initialize s.top to -1

  • To determine whether the stack is full or not the condition s.top==MAXSIZE -1 should be tested. 
  • Also to determine whether or not a stack or not a stack is empty, the condition s.top == -1 should be tested. 

Implementing the POP operation

There is a possibility of underflow in implementing the POP operation, since the user may attempt to POP an element from an empty stack.

To avoid such condition, we should create a function POP that performs the following three actions
  1. If stack is empty, print a warning message & halt the execution. 
  2. Remove the top element from the stack. 
  3. Return this element to the calling program. 

C Code to implement POP



int pop (struct stack *ps)
{
 if (ps -> top == -1){
  printf ("\n Stack Underflow");
  exit(1);
 }

 return (ps -> items[ps -> top--]);

 /* top.item is returned and after that the top is decremented */
}

Implementing PUSH operation

A stack is a dynamic data structure that is constantly allowed to grow and shrink and thus change it's size whereas an array has a predetermined size. 

The array implementation of stack's push operation may thus sometimes outgrow the array size that was set aside to contain the stack.

The situation occurs when the array is full i.e when the stack contains as many elements as the array and an attempt is made to push yet another element onto the stack. The result of such an attempt is called an overflow. 

C code to implement push



void push (struct stack *ps, int r)
{
 if(ps -> top == STACKSIZE-1)
 {
  printf("\n Stack overflow");
  exit(1);
 }

 else{
  printf("\n Enter the value you want to push:");
  scanf("%d,&x");
  ++(ps->top);
  ps-> items [ps-top]=x;
 }
}