堆栈的实现(c语言)

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define EmptyTOS (-1)      //数组堆栈需要 
#define MinStackSize (5)   //数组堆栈需要 


//堆栈函数的声明 
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
typedef int ElementType;

bool IsEmpty(Stack S);                          //检测堆栈是否为空
Stack CreateStack();                            //创建堆栈
void DisposeStack(Stack);                       //毁灭堆栈 
void Push(ElementType X, Stack S);              //元素进栈 
ElementType Pop(Stack S);                       //元素出栈 
void MakeEmpty(Stack S);                        //清空堆栈中的元素
//ElementType Pop(Stack S);                     //元素出栈   (数组实现)
bool IsFull(Stack S);                           //检测堆栈是否已满 (数组实现需要) 
void printStack(Stack S);                       //输出堆栈中的元素 
struct Node {               //链表结构  
	ElementType Element;
	PtrToNode Next;
}; 

//struct Node {               //数组结构  
//	int Capacity;      //容量  
//	int TopOfStack:    //栈顶 
//	ElementType *Array; 
//};



int main()
{
	int number, flag;
	ElementType X;
	Stack S; 
 
	flag = 1;
	
   	printf("|           堆栈的基本使用           |\n");
    printf("|************************************|\n");	
   	printf("|            1. 创建堆栈             |\n");	
   	printf("|            2. 销毁堆栈             |\n");	
   	printf("|            3. 入栈                 |\n");	
   	printf("|            4. 出栈                 |\n");	
   	printf("|            5. 打印堆栈元素         |\n");	
   	printf("|************************************|\n");
   	
    while (flag) {
    printf("请选择功能 :                      \n");
	 	scanf("%d", &number);
		switch(number) {
			case 1 :
				S = CreateStack();
				break; 
			
			case 2 :
				if (S) {
					DisposeStack(S);
				} else 
					printf("堆栈不存在!!!\n"); 
				break;
				
			case 3 :
				if (S) {
					printf("请输入需要插入的元素:");
					scanf("%d", &X);
					Push(X, S); 
				} else
					printf("堆栈不存在!!!\n"); 
				break;
				
			case 4 :
				if (S) {
					Pop(S); 
				} else
					printf("堆栈不存在!!!\n"); 
				break;
				 
			case 5 :
				if (S) {
					printf("堆栈中元素如下:");
					printStack(S); 
				} else
					printf("堆栈不存在!!!\n"); 
				break; 
				
			default :
				printf("程序运行结束,请按任意键退出!!!\n");
				flag = 0;	
			} 
		}  		
		
   return 0; 
}



//函数定义
 
bool IsEmpty(Stack S)                             //检测堆栈是否为空 (链表) 
{
	return S->Next == NULL;
}

//bool IsEmpty(Stack S)                           //检测堆栈是否为空  (数组)
//{
//	return S->TopOfStack == EmptyTOS;
//}

Stack CreateStack()                               //创建堆栈   (链表) 
{
	Stack S;
	
	if (!(S = malloc(sizeof(struct Node))))
		exit(-1);
	S->Next = NULL;
	
	return S;	
 } 
 
// Stack CreateStack(int MaxElements)             //创建堆栈    (数组)
//{
//	Stack S;
//	
//	if (MaxElements < MinStackSize) {
//		printf("堆栈空间太小了!!");
//		return -1; 
//	}
//	
//	if (!(S = malloc(sizeof(struct Node))))
//		exit(-1);
//	if (!(S->Array = malloc(sizeof((ElementType) * MaxStackSize))))
//		exit(-1);
//	S->Capacity = MaxStackSize;
//		
//	return S;	
// } 
 
 void DisposeStack(Stack S)                       //毁灭堆栈 (链表) 
 {
 	PtrToNode P, TmpCell;
 	
 	P = S->Next;
 	S->Next = NULL;
	while (P) {
 		TmpCell = P->Next;
 		free(P);
 		P = TmpCell;
 	}
 	
 	free(S);	
 }
 		
// void DisposeStack(Stack S)                     //毁灭堆栈    (数组) 
// {
// 	if (S != NULL) {
// 		free(S->Array);
// 		free(S);
//	 }	
// } 		
 
void Push(ElementType X, Stack S)                  //元素进栈    (链表) 
{
	PtrToNode TmpCell;
	
	if (!(TmpCell = malloc(sizeof(struct Node))))
		exit(-1);
	else {
		TmpCell->Element = X;
		TmpCell->Next = NULL;
	}
	
	TmpCell->Next = S->Next;
	S->Next = TmpCell;  
}

//void Push(ElementType X, Stack S)                 //元素进栈    (数组) 
//{
//	if (!IsFull(S))
//		S->Array[++TopOfStack] = X;
//	else
//		printf("堆栈已满!!\n");	
//}

ElementType Pop(Stack S)                            //元素出栈    (链表) 
{
	Stack TmpCell;
	ElementType X;
	
	if (IsEmpty(S)) {
		printf("堆栈为空!!!\n");
		return -1;		
	}
	else {
		TmpCell = S->Next;
		S->Next = TmpCell->Next;
		X = TmpCell->Element;   
		free(TmpCell);
		
		return X;
	}
}

//ElementType Pop(Stack S)                          //元素出栈    (数组) 
//{
//	if (!IsEmpty(S))
//		return S->Array[TopOfStack--];
//	else
//		printf("堆栈为空,出栈异常!!!\n");		
//}

void MakeEmpty(Stack S)                             //清空堆栈中的元素    (链表) 
{
	PtrToNode P, TmpCell;
	
	P = S->Next;
	S->Next = NULL;
	while (P) {
		TmpCell = P->Next;
		free(P);
		P = TmpCell; 
	} 
}

//void MakeEmpty(Stack S)                            //清空堆栈中的元素    (数组) 
//{
//	S->TopOfStack == EmptyTOS;
//}

//bool IsFull(Stack S)                               //检测堆栈是否已满 (数组实现需要) 
//{
//	return S->(++TopOfStack) == S->Capacity;
//}
// 
void printStack(Stack S)                             //打印堆栈中元素 
{
	ElementType P;
	while (!IsEmpty(S)) {
		P = Pop(S);
		printf("%d  ", P);
	} 
	printf("\n");
} 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
堆栈在表达式运算中的应用主要是为了处理运算符的优先级和括号的匹配。下面是一个使用堆栈实现表达式运算的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 定义堆栈结构 typedef struct { int top; // 栈顶指针 int *data; // 数据数组 } Stack; // 初始化堆栈 void initStack(Stack *stack, int size) { stack->top = -1; stack->data = (int *)malloc(size * sizeof(int)); } // 判断堆栈是否为空 int isEmpty(Stack *stack) { return stack->top == -1; } // 入栈操作 void push(Stack *stack, int value) { stack->data[++stack->top] = value; } // 出栈操作 int pop(Stack *stack) { return stack->data[stack->top--]; } // 获取栈顶元素 int top(Stack *stack) { return stack->data[stack->top]; } // 判断是否为运算符 int isOperator(char op) { return op == '+' || op == '-' || op == '*' || op == '/'; } // 获取运算符优先级 int getPriority(char op) { if (op == '*' || op == '/') return 2; else if (op == '+' || op == '-') return 1; else return 0; } // 执行表达式运算 int evaluateExpression(char *expression) { Stack operatorStack; // 运算符堆栈 Stack operandStack; // 操作数堆栈 initStack(&operatorStack, 100); initStack(&operandStack, 100); int i = 0; while (expression[i] != '\0') { if (expression[i] == ' ') { i++; continue; } if (isdigit(expression[i])) { int operand = 0; while (isdigit(expression[i])) { operand = operand * 10 + (expression[i] - '0'); i++; } push(&operandStack, operand); } else if (isOperator(expression[i])) { while (!isEmpty(&operatorStack) && getPriority(top(&operatorStack)) >= getPriority(expression[i])) { int op2 = pop(&operandStack); int op1 = pop(&operandStack); char op = pop(&operatorStack); switch (op) { case '+': push(&operandStack, op1 + op2); break; case '-': push(&operandStack, op1 - op2); break; case '*': push(&operandStack, op1 * op2); break; case '/': push(&operandStack, op1 / op2); break; } } push(&operatorStack, expression[i]); i++; } else if (expression[i] == '(') { push(&operatorStack, expression[i]); i++; } else if (expression[i] == ')') { while (!isEmpty(&operatorStack) && top(&operatorStack) != '(') { int op2 = pop(&operandStack); int op1 = pop(&operandStack); char op = pop(&operatorStack); switch (op) { case '+': push(&operandStack, op1 + op2); break; case '-': push(&operandStack, op1 - op2); break; case '*': push(&operandStack, op1 * op2); break; case '/': push(&operandStack, op1 / op2); break; } } pop(&operatorStack); // 弹出左括号 i++; } } while (!isEmpty(&operatorStack)) { int op2 = pop(&operandStack); int op1 = pop(&operandStack); char op = pop(&operatorStack); switch (op) { case '+': push(&operandStack, op1 + op2); break; case '-': push(&operandStack, op1 - op2); break; case '*': push(&operandStack, op1 * op2); break; case '/': push(&operandStack, op1 / op2); break; } } int result = pop(&operandStack); free(operatorStack.data); free(operandStack.data); return result; } int main() { char expression[100]; printf("请输入表达式:"); gets(expression); int result = evaluateExpression(expression); printf("计算结果:%d\n", result); return 0; } ``` 以上代码实现了对输入的表达式进行运算,其中使用两个堆栈分别存储运算符和操作数。通过比较运算符的优先级来决定是否进行运算,并将结果压入操作数堆栈中。最终得到的操作数堆栈中的唯一元素即为表达式的计算结果。请注意,在输入表达式时需要注意空格的处理,以方便程序的解析。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值