PROGRAM - 19
Write a program to implement stack operations using:
- Arrays.
- Pointers.
Program to implement stack operations using arrays:
#include<stdio.h>
#include<conio.h>
#define max 5
static stack(max);
int top;
void push(int t)
{
if(top>=max)
{
printf("stack is full");
return;
}
stack[top++]=t;
}
int pop()
{
top--;
if(top<0)
{
printf("stack is empty");
}
return(stack[top]);
}
main()
{
int condition,element,ret;
clrscr();
while(1)
{
printf("enter-1:push\n");
printf("enter-2:pop\n");
printf("enter-3:exit\n");
scanf("%d",&condition);
switch(condition)
{
case 1:printf("enter the element to push");
scanf("%d",&elements);
push(element);
break;
case 2:ret=pop();
printf("popped element is %d",ret);
break;
case 3:return 0;
default:printf("\n choose & give correct option");
}
}
getch();
return();
}
Program to implement stack operations using pointers:
#include<stdio.h>
#include<conio.h>
struct stack
{
int data;
struct stack *next;
};
typedef struct stack node;
node *start=NULL;
node *top=NULL;
node *getnode();
int menu();
void push(node*);
void pop();
void display();
void main()
{
node *newnode;
int ch;
clrscr();
do
{
ch=menu();
switch(ch)
{
case 1:{
newnode=getnode();
push(newnode);
}
break;
case 2:pop();
break;
case 3:display();
break;
case 4:exit(1);
default:printf("invalid choice");
}
}while(1);
}
int menu()
{
int ch;
printf("menu\n");
printf("1.push\n");
printf("2.pop\n");
printf("3.display\n");
printf("4.exit\n");
printf("enter your choice");
scanf("%d",&ch);
return ch;
}
node *getnode()
{
node *newnode;
newnode=(node*)malloc(sizeof(node));
printf("enter the data");
scanf("%d",&newnode->data);
newnode->next=NULL;
return(newnode);
}
void push(node *newnode)
{
node *temp;
if(newnode==NULL)
{
printf("overflow");
}
else
{
if(start==NULL)
{
start=newnode;
top=newnode;
}
else
{
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
top=newnode;
}
}
}
void pop()
{
node *temp;
if(start==NULL)
{
printf("underflow");
}
else
{
if(start->next==NULL)
{
printf("popped element is %d",top->data);
start=NULL;
free(top);
top=NULL;
}
else
{
temp=start;
while(temp->next!=top)
{
temp=temp->next;
}
temp->next=NULL;
printf("popped element is %d",top->data);
free(top);
top=temp;
}
}
}
void display()
{
node *temp;
temp=start;
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}