-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_using_queue.c
More file actions
103 lines (94 loc) · 2.13 KB
/
stack_using_queue.c
File metadata and controls
103 lines (94 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <stdio.h>
#include <stdlib.h>
#define max 100
struct queue {
int arr[max];
int front, rear;
};
void initQueue(struct queue* q) {
q->front = q->rear = -1;
}
int isEmpty(struct queue* q) {
return (q->front == -1);
}
void enqueue(struct queue* q, int data) {
if (q->rear == max - 1) {
printf("Queue is full\n");
return;
}
if (isEmpty(q)) {
q->front = 0;
}
q->rear++;
q->arr[q->rear] = data;
}
int dequeue(struct queue * q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return -1;
}
int item = q->arr[q->front];
if (q->front == q->rear) {
q->front = q->rear = -1;
} else {
q->front++;
}
return item;
}
void push(struct queue * q, int data) {
enqueue(q, data);
}
int pop(struct queue* q) {
if (isEmpty(q)) {
printf("Stack Underflow\n");
return -1;
}
int size = q->rear - q->front + 1;
for (int i = 0; i < size - 1; i++) {
enqueue(q, dequeue(q));
}
return dequeue(q);
}
int top(struct queue* q) {
if (isEmpty(q)) {
printf("Stack is empty\n");
return -1;
}
int size = q->rear - q->front + 1;
int lastElement;
for (int i = 0; i < size; i++) {
lastElement = dequeue(q);
enqueue(q, lastElement);
}
return lastElement;
}
int main() {
struct queue *stack = (struct queue*)malloc(sizeof(struct queue));
initQueue(stack);
int x, ch, data;
while(1)
{
printf("1.Push\n2.Pop\n3.Peek\n4.Exit\n");
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter element: ");
scanf("%d",&data);
push(stack, data);
break;
case 2:
pop(stack);
break;
case 3:
x = top(stack);
printf("The top element of the stack is: %d\n",x);
break;
case 4:
exit(0);
break;
}
}
return 0;
}