C++ or C Program for Push, Pop, Peek operations of Stack data structure.

File Name:- stack.cpp

#include<iostream.h>
#include<conio.h>
#define N 5
int stack[N],item, top=-1;
//push function
void push(){
if(top==N-1){
cout<<"Overflow Condition"<<endl;
getch();
return;
}
cout<<"Enter an Item to push"<<endl;
cin>>item;
top++;
stack[top]=item;
cout<<"item="<<item<<"is pushed\npush completed"<<endl;
getch();
return;
}
//pop function
void pop(){
if(top==-1){
cout<<"underflow Condition"<<endl;
getch();
return;
}
item=stack[top];
top--;
cout<<"item="<<item<<" is popped\npop completed"<<endl;
getch();
return;
}
//peekfunction
void peek(){
int i;
if(top==-1){
cout<<"Stack is Empty"<<endl;
getch();
return;
}
else{
cout<<"Top of the stack is="<<stack[top]<<endl<<"Top="<<top<<endl<<"peek completed"<<endl;
getch();
return;
}
//main function
void main(){
int ch;
while(1){
clrscr();
cout<<"Stack Operation:-\n1.PUSH\n2.POP\n3.PEEK\n4.EXIT\nenter your choice"<<endl;
cin>>ch;
switch(ch){
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
exit();
default:
cout<<"Wrong Choice\nTry Again !!"<<endl;
getch();
}}}

File Name:- stack.c

#include<stdio.h>
#include<conio.h>
#define N 5
int stack[N],top=-1,item;
void push(){
if(top==N-1){
printf("Overflow Condition\n");
getch();
return;
}
printf("Enter an Item to insert\n");
scanf("%d",&item);
top++;
stack[top]=item;
printf("push completed\n");
getch();
return;
}
void pop(){
if(top==-1){
printf("underflow Condition\n");
getch();
return;
}
item=stack[top];
top--;
printf("pop completed\n");
getch();
return;
}
void peek(){
int i;
if(top==-1){
printf("Stack is Empty\n");
getch();
return;
}
printf("Top element of the stack is %d\nTop=%d \npeek completed",stack[top],top);
getch();
return;
}
void main(){
int ch;
while(1){
clrscr();
printf("Stack Operation:-\n1.PUSH\n2.POP\n3.PEEK\n4.EXIT\nenter your choice\n");
scanf("%d",&ch);
switch(ch){
case 1: push();break;
case 2: pop();break;
case 3: peek();break;
case 4:
exit();
}
}
}

No comments:

Post a Comment

Stack Data Structure, Push, Pop and Peek Operations , Applications of Stack

Stack is a linear data structure. It is collection of ordered data elements. It is also known as LIFO system (last in first out). It means i...