Вы находитесь на странице: 1из 19

Implementing a Stack Using an

Array
Header files

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

D. Wint 2017
Constant Variable and Structure

#define size 5
struct stack {
int s[size];
int top;
} st;
D. Wint 2017
int stfull() {
if (st.top >= size - 1)
return 1;
else
return 0;
}
D. Wint 2017
void push(int item) {
st.top++;
st.s[st.top] = item;
}
D. Wint 2017
int stempty() {
if (st.top == -1)
return 1;
else
return 0;
}
D. Wint 2017
int pop() {
int item;
item = st.s[st.top];
st.top--;
return (item);
}
D. Wint 2017
void display() {
int i;
if (stempty())
printf("\nStack Is Empty!");
else {
for (i = st.top; i >= 0; i--)
printf("\n%d", st.s[i]);
}
} D. Wint 2017
int main() {
int item, choice;
char ans;
st.top = -1;

printf("\n\tImplementation Of Stack");
do {
printf("\nMain Menu");
printf("\n1.Push \n2.Pop \n3.Display \n4.exit");
printf("\nEnter Your Choice");
scanf("%d", &choice);D. Wint 2017
switch (choice) {
case 1:
printf("\nEnter The item to be pushed");
scanf("%d", &item);
if (stfull())
printf("\nStack is Full!");
else
push(item);
break;
D. Wint 2017
case 2:
if (stempty())
printf("\nEmpty stack!Underflow !!");
else {
item = pop();
printf("\nThe popped element is %d", item);
}
break;
D. Wint 2017
case 3:
display();
break;
case 4:
exit(0);
}
printf("\nDo You want To Continue?");
ans = getche();
} while (ans == 'Y' || ans == 'y');

return 0;
}
D. Wint 2017
QUEUE USING ARRAY
#include <stdio.h>

#define MAX 50
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /*End of switch*/
} /*End of while*/
insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /*End of insert()*/
delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /*End of delete() */
display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /*End of display() */

Вам также может понравиться