Programming Geek
Rated 4.7/5 based on 1446 reviews

Stack Implementation in C

Stack is a "last in first out" (LIFO) data structure in which the last element added is the first element to be removed. The addition of an element on stack is called PUSH and the deletion of the element is called POP operation. A typical stack is illustrated below:


Stack finds a large number of applications in various area of computer science like stack area during execution of a program, tower of Hanoi or any other recursive program.

Some stack terminology are:

PUSH : It is the process of adding an element at the top of the stack. If stack is full then stack overflow error is shown i.e. no more elements can be added.

POP : It is the process of removing an element from the top of the stack, If stack is empty then stack underflow error is shown i.e. no element can be deleted.

TOP : It always points to the top of the stack.

An implementation of stack in c is as below:

#include<stdio.h>
#include<stdlib.h>

typedef struct stack
{
 int size;
 int capacity;
 int*elements;
}stack;

stack*init(int max_elements)
{
 stack*s=(stack*)malloc(sizeof(stack));
 s->capacity=max_elements;
 s->size=0;
 s->elements=(int*)malloc(sizeof(int)*max_elements);
 return s;
}

void push(stack*s,int num)
{
 if(s->size==s->capacity)
 {
  printf("\n stack is full!!!");
  return;
 }
 s->elements[s->size++]=num;
 
}

void pop(stack*s)
{
 if(s->size==0)
 {
  printf("\nstack is empty!!!");
  return;
 }
 s->size--;
}

int top(stack*s)
{
 if(!s->size)
 {
  printf("\nstack is empty!!!");
  exit(0);
 }
 return s->elements[s->size-1];
 
}

void main()
{
 stack *s = init(9);
        push(s,12);
        push(s,15);
        push(s,58);
        push(s,32);
        printf("Top element is %d\n",top(s));
        pop(s);
        printf("Top element is %d\n",top(s));
        pop(s);
        printf("Top element is %d\n",top(s));
        pop(s);
        printf("Top element is %d\n",top(s));


}

No comments :

Post a Comment