Thursday 13 August 2015

DS: stacks

STACKS:

A stack is a special type of data structure where elements are inserted from one end and elements are deleted from the same end.
Using this approach, the Last element Inserted is the First element to be deleted out(FIFO).


Various operations:
1. Stack Create(STACK_SIZE)
2. Boolean IsFull(s,STACK_SIZE)
3.Stack Push(s,iem)
4,Boolean IsEmpty(s)
5.Element Pop(s)

C program to implement stack.. (STATIC MEMORY ALLOCATION)

#include<stdio.h>
#define MAX 10
int top=-1;

int isfull()
{
if(top==MAX-1) return 1;
else return 0;

}

int isempty()
{
if(top==-1) return 1;
else return 0;
}
void push(int item, int s[])
{
if(isfull()) printf("stack is full \n");
else
{
top=top+1;
s[top]=item;
}
}

void pop(int s[])
{
if(isempty()) printf("no elements in d stack to pop \n");
else
{
printf("element poped it %d",s[top]);
top--;
}
}

void display(int s[])
{
int i;
if(isempty()) printf("stack is empty \n");
else{
for(i=0;i<=top;i++)
printf("%d \n",s[i]);
}
}
void main()
{
int s[MAX];
int item,n;
for(;;)
{
printf("select your choice \n");
printf("1.PUSH 2.POP 3.DISPLAY 4.EXIT \n");
scanf("%d",&n);

switch(n)
{
case 1: printf("enter the elemen to be inserted \n");
scanf("%d",&item);
push(item,s);
break;
case 2: printf("pop operation is selected \n");
pop(s);
break;
case 3: printf("content of the stack are \n");
display(s);
break;
case 4:exit(0); break;
}
}
}

No comments:

Post a Comment

Total Pageviews