要求用户给出元素个数以及元素的内容,元素为整数,将其中的奇数顺序逆置,偶数顺序保持不变,给出完整c++代码,要求用到栈相关内容
时间: 2024-06-04 07:12:08 浏览: 53
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int stackEmpty(Stack *s) {
return s->top == -1;
}
int stackFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, int x) {
if (stackFull(s)) {
printf("Stack overflow!\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (stackEmpty(s)) {
printf("Stack underflow!\n");
exit(1);
}
return s->data[s->top--];
}
int peek(Stack *s) {
if (stackEmpty(s)) {
printf("Stack underflow!\n");
exit(1);
}
return s->data[s->top];
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
Stack s;
initStack(&s);
printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
if (x % 2 == 0) {
push(&s, x);
}
}
printf("The modified sequence is:\n");
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
if (x % 2 == 1) {
printf("%d ", x);
} else {
printf("%d ", pop(&s));
}
}
return 0;
}
阅读全文