Sunday, January 25, 2015

Stack implementation in C language.

Given below is a simple stack implementation in C language. Three main functions of a stack are implemented here, namely push, pop and top.
#include <stdio.h>
#include <stdlib.h>
int top;
int push( int temp , int *arr)
{
if(top >10 )
{
printf("stack is full\n");
return -1;
}
if(arr == NULL)
{
printf("stack is empty\n");
top = 1;
arr[0] = temp;
return 1;
}
else
{
top = top + 1;
arr[top] = temp;
return 1;
}
}
int pop(int *arr)
{
int temp = 0;
if(arr == NULL)
{
printf("stack doesnt exist\n");
return -1;
}
if(top == 0)
{
printf("stack is empty\n");
return -1;
}
else if (top > 0)
{
temp = arr[top];
top = top - 1;
return temp;
}
else
{
printf("Invalid top value\n");
return -1;
}
}
int topstack(int *arr)
{
if(arr == NULL)
{
printf("stack doesnt exist\n");
return -1;
}
if(top >= 0)
{
return arr[top];
}
else
{
printf("Invalid top value\n");
return -1;
}
}
int main()
{
int *arr;
int popvalue;
top = 0;
arr = (int *) malloc (sizeof(10));
push(1,arr);
push(2,arr);
push(3,arr);
push(4,arr);
push(5,arr);
push(6,arr);
push(7,arr);
push(8,arr);
push(9,arr);
push(10,arr);
push(11,arr);
push(12,arr);
printf("Popped value %d \n",pop(arr) );
printf("Popped value %d \n",pop(arr) );
printf("Popped value %d \n",pop(arr) );
printf("Top value %d \n",topstack(arr));
getchar();
return 0;
}
view raw stack.c hosted with ❤ by GitHub

No comments:

Post a Comment