棧的應用-字尾表示式求解
阿新 • • 發佈:2018-12-22
# ifndef LINKSTACK_H # define LINKSTACK_H # include <stdio.h> # include <string.h> # include <stdlib.h> //鏈式棧的結點 typedef struct LINKNODE { struct LINKNODE* next; }LinkNode; //鏈式棧 typedef struct LINKSTACK { LinkNode head; int size; }LinkStack; //初始化函式 LinkStack* Init_LinkStack(); //入棧 void Push_LinkStack(LinkStack* stack, LinkNode* data); //出棧 void Pop_LinkStack(LinkStack* stack); //返回棧頂元素 LinkNode* Top_LinkStack(LinkStack* stack); //返回棧元素的個數 int Size_LinkStack(LinkStack* stack); //清空棧 void Clear_SeqStack(LinkStack* stack); //銷燬 void FreeSpace_SeqStack(LinkStack* stack); # endif # include "LinkStack.h" //初始化函式 LinkStack* Init_LinkStack() { LinkStack* stack = (LinkStack*)malloc(sizeof(LinkStack)); stack->head.next = NULL; stack->size = 0; return stack; } //入棧 void Push_LinkStack(LinkStack* stack, LinkNode* data) { if(stack == NULL) { return ; } if(data == NULL) { return ; } data->next = stack->head.next; stack->head.next = data; stack->size++; } //出棧 void Pop_LinkStack(LinkStack* stack) { if(stack == NULL) { return ; } if(stack->size == 0) { return ; } //第一個有效結點 LinkNode* pNext = stack->head.next; stack->head.next = pNext->next; stack->size--; } //返回棧頂元素 LinkNode* Top_LinkStack(LinkStack* stack) { if(stack == NULL) { return NULL; } if(stack->size == 0) { return NULL; } return stack->head.next; } //返回棧元素的個數 int Size_LinkStack(LinkStack* stack) { if(stack == NULL) { return -1; } return stack->size; } //清空棧 void Clear_SeqStack(LinkStack* stack) { if(stack == NULL) { return ; } stack->head.next = NULL; stack->size = 0; } //銷燬 void FreeSpace_SeqStack(LinkStack* stack) { if(stack == NULL) { return ; } } # include "LinkStack.h" //判斷是不是數字 int IsNumber(char c) { return c >= '0' && c <= '9'; } typedef struct MYNUM { LinkNode node; int val; }MyNum; //計算 int Caculate(int left, int right, char c) { int ret = 0; switch(c) { case '+': ret = left + right; break; case '-': ret = left - right; break; case '*': ret = left * right; break; case '/': ret = left / right; break; default: break; } return ret; } int main(int argc, char *argv[]) { //字尾表示式 char* str = "831-5*+"; char* p = str; //建立棧 LinkStack* stack = Init_LinkStack(); while(*p != '\0') { //如果是數字 直接入棧 if(IsNumber(*p)) { MyNum* num = (MyNum*)malloc(sizeof(MyNum)); num->val = *p - '0'; Push_LinkStack(stack, (LinkNode*)num); } else { //先從棧中彈出右運算元 MyNum* right = (MyNum*)Top_LinkStack(stack); int rightNum = right->val; Pop_LinkStack(stack); free(right);; //取出左運算元 MyNum* left = (MyNum*)Top_LinkStack(stack); int leftNum = left->val; Pop_LinkStack(stack); free(left); int ret = Caculate(leftNum, rightNum, *p); //結果入棧 MyNum* num = (MyNum*)malloc(sizeof(MyNum)); num->val = ret; Push_LinkStack(stack, (LinkNode*)num); } p++; } if(Size_LinkStack(stack) == 1) { MyNum* num = (MyNum*)Top_LinkStack(stack); printf("運算結果是:%d\n", num->val); Pop_LinkStack(stack); free(num); } //釋放棧 FreeSpace_SeqStack(stack); return 0; }