栈实现加减乘除
實(shí)現(xiàn)這個(gè)算法首先要定義兩個(gè)結(jié)構(gòu)體,一個(gè)結(jié)點(diǎn)結(jié)構(gòu)體,一個(gè)棧結(jié)構(gòu)體,然后就是一系列的基本操作,初始化入棧出棧,核心部分就是兩個(gè),一個(gè)就是運(yùn)算符的優(yōu)先級(jí),需要分情況討論;另一個(gè)就是出入棧問題,既要兼顧優(yōu)先級(jí)又要兼顧括號(hào)匹配,有進(jìn)棧不運(yùn)算、進(jìn)棧運(yùn)算 、出棧不運(yùn)算、出棧運(yùn)算幾種情況。具體請(qǐng)看代碼:
#include <stdio.h>
#include <stdlib.h>#define OK 1
#define ERROR 0/* 定義結(jié)點(diǎn)結(jié)構(gòu)體 */
typedef struct node
{int data;struct node *next;
}Node;/* 定義棧結(jié)構(gòu)體 */
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;
}/* 進(jìn)棧 */
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);
}/* 自定義優(yōu)先級(jí) */
int Priority(char s)
{switch(s){case '(': //括號(hào)優(yōu)先級(jí)最高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("請(qǐng)輸入你想要的操作:\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{//進(jìn)棧不運(yùn)算if((EmptyStack(&opt) == OK) || (GetTop(&opt) == '(' && str[i] != ')') ||Priority(str[i]) > Priority(GetTop(&opt))) {Push(&opt, str[i]);i++;continue;}//出棧不運(yùn)算if (GetTop(&opt) == '(' && str[i] == ')'){Pop(&opt);i++;continue;}//出棧運(yùn)算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));}
總結(jié)
- 上一篇: 快速排序原理剖析
- 下一篇: 时序产生器和控制方式