c语言编程代码,以菜单选择的形式,实现栈的创建,入队,出队,退出等功能
时间: 2024-05-06 18:21:11 浏览: 21
好的,这是一个关于栈的数据结构的问题,我可以回答。下面是一份示例代码,它包含了栈的创建、入栈、出栈和退出等功能。
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 100
typedef struct {
int data[MAX_STACK_SIZE];
int top;
} Stack;
Stack* createStack()
{
Stack* s = (Stack*) malloc(sizeof(Stack));
s->top = -1;
return s;
}
int isEmpty(Stack* s)
{
return s->top == -1;
}
int isFull(Stack* s)
{
return s->top == MAX_STACK_SIZE - 1;
}
void push(Stack* s, int x)
{
if (isFull(s)) {
printf("Error: stack is full\n");
return;
}
s->top++;
s->data[s->top] = x;
}
int pop(Stack* s)
{
if (isEmpty(s)) {
printf("Error: stack is empty\n");
return -1;
}
int x = s->data[s->top];
s->top--;
return x;
}
void printStack(Stack* s)
{
printf("Stack contents:");
for (int i = s->top; i >= 0; i--) {
printf(" %d", s->data[i]);
}
printf("\n");
}
void freeStack(Stack* s)
{
free(s);
}
int main()
{
Stack* s = createStack();
int choice, x;
do {
printf("Menu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Print stack\n");
printf("4. Quit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &x);
push(s, x);
break;
case 2:
x = pop(s);
if (x != -1) {
printf("Popped value: %d\n", x);
}
break;
case 3:
printStack(s);
break;
case 4:
// Quit
break;
default:
printf("Invalid choice\n");
break;
}
} while (choice != 4);
freeStack(s);
return 0;
}
```
希望这个代码能够帮到你!