-
Notifications
You must be signed in to change notification settings - Fork 0
/
qmax.c
138 lines (126 loc) · 2.76 KB
/
qmax.c
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
int max;
int data;
struct node* next;
};
void push(struct node** top, int data);
int pop(struct node** top);
struct queue {
struct node* stack1;
struct node* stack2;
};
struct queue* initQueue() {
struct queue* queue = (struct queue*)malloc(sizeof(struct queue));
queue->stack1 = NULL;
queue->stack2 = NULL;
return queue;
}
void enqueue(struct queue* q, int x) { push(&q->stack1, x); }
void dequeue(struct queue* q) {
int x;
if (q->stack1 == NULL && q->stack2 == NULL) {
printf("Î÷åðåäü ïóñòà\n");
return;
}
if (q->stack2 == NULL) {
while (q->stack1 != NULL) {
x = pop(&q->stack1);
push(&q->stack2, x);
}
}
x = pop(&q->stack2);
printf("%d\n", x);
}
void queueEmpty(struct queue* q) {
if (q->stack1 == NULL && q->stack2 == NULL) {
printf("true\n");
return;
} else {
printf("false\n");
return;
}
}
void maximum(struct queue* q) {
if (q->stack1 == NULL && q->stack2 == NULL) {
printf("Î÷åðåäü ïóñòà\n");
return;
}
if (q->stack1 == NULL) {
printf("%d\n", q->stack2->max);
} else if (q->stack2 == NULL) {
printf("%d\n", q->stack1->max);
} else {
if (q->stack1->max > q->stack2->max) {
printf("%d\n", q->stack1->max);
} else {
printf("%d\n", q->stack2->max);
}
}
}
void push(struct node** top, int data) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
if (newnode == NULL) {
printf("Stack overflow \n");
}
if ((*top) == NULL) {
newnode->max = data;
} else {
if ((*top)->max < data && (*top) != NULL) {
newnode->max = data;
} else {
newnode->max = (*top)->max;
}
}
newnode->data = data;
newnode->next = (*top);
(*top) = newnode;
}
int pop(struct node** top) {
int buff;
struct node* t;
if (*top == NULL) {
printf("Stack underflow \n");
} else {
t = *top;
buff = t->data;
*top = t->next;
free(t);
return buff;
}
}
void queuefree(struct queue* q) {
while (q->stack1 != NULL) {
pop(&q->stack1);
}
while (q->stack2 != NULL) {
pop(&q->stack2);
}
}
int main() {
int a, n;
char str[10];
struct queue* q = initQueue();
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s", str);
if (strstr(str, "ENQ")) {
scanf("%d", &a);
enqueue(q, a);
} else if (strstr(str, "DEQ")) {
dequeue(q);
} else if (strstr(str, "MAX")) {
maximum(q);
} else if (strstr(str, "EMPTY")) {
queueEmpty(q);
} else {
printf("Îøèáêà\n");
}
}
queuefree(q);
free(q);
return 0;
}