栈实现加减乘除
實現這個算法首先要定義兩個結構體,一個結點結構體,一個棧結構體,然后就是一系列的基本操作,初始化入棧出棧,核心部分就是兩個,一個就是運算符的優先級,需要分情況討論;另一個就是出入棧問題,既要兼顧優先級又要兼顧括號匹配,有進棧不運算、進棧運算 、出棧不運算、出棧運算幾種情況。具體請看代碼:
#include <stdio.h>
#include <stdlib.h>#define OK 1
#define ERROR 0/* 定義結點結構體 */
typedef struct node
{int data;struct node *next;
}Node;/* 定義棧結構體 */
typedef struct stack
{Node *top;int count;
}Stack;/* 初始化棧 */
int InitStack(Stack *S)
{S->top = NULL;S->count = 0;return OK;
}/* 判斷棧空 */
int EmptyStack(Stack *S)
{return (S->count == 0) ? OK : ERROR;
}/* 進棧 */
int Push(Stack *S, int e)
{Node *p = (Node *)malloc(sizeof(Node));if(p == NULL){return ERROR;}p->data = e;p->next = S->top;S->top = p;S->count++;return OK;
}/* 獲取棧頂 */
int GetTop(Stack *S)
{if(NULL == S->top)return ERROR;return (S->top->data);
}/* 自定義優先級 */
int Priority(char s)
{switch(s){case '(': //括號優先級最高return 3;case '*':case '/': //乘除次之return 2;case '+':case '-': //加減最低return 1; default :return 0;}
}/* 出棧 */
int Pop(Stack *S)
{int e;if (NULL == S->top)return ERROR;Node *p = S->top;e = p->data;S->top = p->next;free(p);S->count--;return e;
}int main()
{Stack num, opt;char str[100] = {0};int i = 0, tmp = 0, j;if (InitStack(&num) != OK || InitStack(&opt) !=OK){printf("Init Failure!\n");exit(1);}printf("請輸入你想要的操作:\n");scanf("%s", str);while (str[i] != '\0' || EmptyStack(&opt) != OK){if(str[i] >= '0' && str[i] <= '9'){tmp = tmp *10 + str[i] -'0';i++;if(str[i] < '0' || str[i] > '9'){Push(&num, tmp);tmp = 0;}}else{//進棧不運算if((EmptyStack(&opt) == OK) || (GetTop(&opt) == '(' && str[i] != ')') ||Priority(str[i]) > Priority(GetTop(&opt))) {Push(&opt, str[i]);i++;continue;}//出棧不運算if (GetTop(&opt) == '(' && str[i] == ')'){Pop(&opt);i++;continue;}//出棧運算if ((str[i] != '\0' && EmptyStack(&opt) != OK) || (str[i] == ')' && GetTop(&opt)!= '(') || Priority(str[i]) <= Priority(GetTop(&opt))){switch (Pop(&opt)){case '+':Push(&num, Pop(&num) + Pop(&num));break;case '-':j = Pop(&num);Push(&num, Pop(&num) - j);break;case '*':Push(&num, Pop(&num) * Pop(&num));break;case '/':j = Pop(&num);Push(&num, Pop(&num) / j);break;}continue;}}}printf("result is:%d\n",Pop(&num));}
總結
- 上一篇: 快速排序原理剖析
- 下一篇: 时序产生器和控制方式