在主程序中调用如下函数实现栈的初始化,在栈中插入数值,最后输出栈中元素。 1.函数,Status InitStack(SqStack *S) ,构造一个空栈,成功返回OK,否则返回ERROR。 2.函数,void StackPrint(SqStack S),和push方法,实现在屏幕上输出栈中的元素和插入元素。 3.函数,translate(int data,int index1,index2),实现进制转换,index1代表源数据进制,index2代表目标进制, 4.函数,int Menu(),输出菜单项 •请选择你要进行的操作(请输入1-5中的任一个数字):输入 1:InitStack •2:StackPrint •3:Exit,4push,5translate
时间: 2024-03-17 17:40:13 浏览: 12
好的,以下是您需要的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
typedef int Status;
typedef int ElemType;
typedef struct {
ElemType *base;
ElemType *top;
int stacksize;
} SqStack;
// 构造一个空栈
Status InitStack(SqStack *S) {
S->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!S->base) {
exit(1);
}
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return 0;
}
// 将元素压入栈中
Status Push(SqStack *S, ElemType e) {
if (S->top - S->base >= S->stacksize) {
S->base = (ElemType *)realloc(S->base, (S->stacksize + STACK_INCREMENT) * sizeof(ElemType));
if (!S->base) {
exit(1);
}
S->top = S->base + S->stacksize;
S->stacksize += STACK_INCREMENT;
}
*(S->top)++ = e;
return 0;
}
// 输出栈中元素
void StackPrint(SqStack S) {
printf("Stack elements: ");
while (S.top > S.base) {
printf("%d ", *--S.top);
}
printf("\n");
}
// 进制转换
int translate(int data, int index1, int index2) {
int result = 0, weight = 1;
while (data != 0) {
result += (data % index2) * weight;
data /= index2;
weight *= index1;
}
return result;
}
// 主菜单
int Menu() {
int choice;
printf("Please select an operation:\n");
printf("1: Initialize stack\n");
printf("2: Print stack\n");
printf("3: Exit\n");
printf("4: Push\n");
printf("5: Translate\n");
scanf("%d", &choice);
return choice;
}
int main() {
SqStack S;
InitStack(&S);
int choice;
do {
choice = Menu();
switch (choice) {
case 1: {
InitStack(&S);
printf("Stack initialized.\n");
break;
}
case 2: {
StackPrint(S);
break;
}
case 3: {
printf("Exiting...\n");
break;
}
case 4: {
printf("Enter a number to push onto the stack: ");
int num;
scanf("%d", &num);
Push(&S, num);
printf("%d has been pushed onto the stack.\n", num);
break;
}
case 5: {
printf("Enter a number to translate: ");
int num, index1, index2;
scanf("%d", &num);
printf("Enter the source radix: ");
scanf("%d", &index1);
printf("Enter the target radix: ");
scanf("%d", &index2);
int result = translate(num, index1, index2);
printf("%d in radix %d is equal to %d in radix %d.\n", num, index1, result, index2);
break;
}
default: {
printf("Invalid choice. Please try again.\n");
break;
}
}
} while (choice != 3);
return 0;
}
```
在主函数中,我们首先调用 `InitStack` 函数初始化栈,然后在菜单中提供了五个选项,包括初始化栈、输出栈中元素、退出程序、将元素压入栈中和进行进制转换。根据用户的选择,我们调用相应的函数来完成操作。其中,压入元素的操作使用了 `Push` 函数,进制转换的操作使用了 `translate` 函数。最后,我们在主函数返回之前释放了动态分配的内存。