int main() { int Maxsize=100; Stack s=CreateStack(Maxsize); int i=1,j=1,choice,val,n; char a;根据刚才分析的思路写完C语言
时间: 2024-05-31 13:07:48 浏览: 100
大数运算器(c写的)
代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ERROR -1
typedef int ElementType;
typedef struct SNode *PtrToSNode;
struct SNode {
ElementType *Data;
int Top;
int MaxSize;
};
typedef PtrToSNode Stack;
Stack CreateStack(int MaxSize);
bool IsFull(Stack S);
bool IsEmpty(Stack S);
bool Push(Stack S, ElementType X);
ElementType Pop(Stack S);
void PrintStack(Stack S);
int main() {
int Maxsize=100;
Stack s=CreateStack(Maxsize);
int i=1,j=1,choice,val,n;
char a;
do {
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Print stack\n");
printf("0. Exit\n");
printf("Please enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Please enter a value to push: ");
scanf("%d", &val);
if (Push(s, val)) {
printf("Push %d success.\n", val);
} else {
printf("Push failed, stack is full.\n");
}
break;
case 2:
val = Pop(s);
if (val != ERROR) {
printf("Pop %d success.\n", val);
} else {
printf("Pop failed, stack is empty.\n");
}
break;
case 3:
printf("The stack is: ");
PrintStack(s);
break;
case 0:
break;
default:
printf("Invalid choice.\n");
break;
}
} while (choice != 0);
return 0;
}
Stack CreateStack(int MaxSize) {
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Data=(ElementType*)malloc(MaxSize*sizeof(ElementType));
S->Top=-1;
S->MaxSize=MaxSize;
return S;
}
bool IsFull(Stack S) {
return (S->Top==S->MaxSize-1);
}
bool IsEmpty(Stack S) {
return (S->Top==-1);
}
bool Push(Stack S, ElementType X) {
if (IsFull(S)) {
return false;
} else {
S->Data[++(S->Top)]=X;
return true;
}
}
ElementType Pop(Stack S) {
if (IsEmpty(S)) {
return ERROR;
} else {
return S->Data[(S->Top)--];
}
}
void PrintStack(Stack S) {
int i;
for (i=S->Top; i>=0; i--) {
printf("%d ", S->Data[i]);
}
printf("\n");
}
阅读全文