用C语言编写完整代码:一个能够保存1024个整数的整型顺序栈,可以实现以下功能:(1)初始化栈 (2)显示栈顶元素 (3)将一个元素入栈 (4)从栈中弹出一个元素 (5)判栈是否为空 (6)判栈是否为满
时间: 2024-05-22 10:15:06 浏览: 96
抱歉,我可以回答您的问题。以下是用C语言编写完整代码实现一个能够保存1024个整数的整型顺序栈,可以实现以下功能:
#include <stdio.h>
#define MAXSIZE 1024
struct Stack {
int data[MAXSIZE];
int top;
};
void initStack(struct Stack* s) {
s->top = -1;
}
int isEmpty(struct Stack s) {
return s.top == -1;
}
int isFull(struct Stack s) {
return s.top == MAXSIZE - 1;
}
void push(struct Stack* s, int x) {
if (isFull(*s)) {
printf("Error: Stack is full\n");
return;
}
s->data[++(s->top)] = x;
}
int pop(struct Stack* s) {
if (isEmpty(*s)) {
printf("Error: Stack is empty\n");
return -1;
}
return s->data[(s->top)--];
}
int peek(struct Stack s) {
if (isEmpty(s)) {
printf("Error: Stack is empty\n");
return -1;
}
return s.data[s.top];
}
int main() {
struct Stack s;
int choice, x;
initStack(&s);
do {
printf("\n1. Push an element");
printf("\n2. Pop an element");
printf("\n3. Display top element");
printf("\n4. Check if stack is empty");
printf("\n5. Check if stack is full");
printf("\n6. Exit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter element to push: ");
scanf("%d", &x);
push(&s, x);
break;
case 2:
printf("Popped element: %d\n", pop(&s));
break;
case 3:
printf("Top element: %d\n", peek(s));
break;
case 4:
if (isEmpty(s)) {
printf("Stack is empty\n");
} else {
printf("Stack is not empty\n");
}
break;
case 5:
if (isFull(s)) {
printf("Stack is full\n");
} else {
printf("Stack is not full\n");
}
break;
case 6:
printf("Exiting...\n");
break;
default:
printf("Invalid choice\n");
break;
}
} while (choice != 6);
return 0;
}
阅读全文