SDUT-2132_数据结构实验之栈与队列二:一般算术表达式转换成后缀式
生活随笔
收集整理的這篇文章主要介紹了
SDUT-2132_数据结构实验之栈与队列二:一般算术表达式转换成后缀式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
數(shù)據(jù)結(jié)構(gòu)實驗之棧與隊列二:一般算術(shù)表達(dá)式轉(zhuǎn)換成后綴式
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
對于一個基于二元運算符的算術(shù)表達(dá)式,轉(zhuǎn)換為對應(yīng)的后綴式,并輸出之。
Input
輸入一個算術(shù)表達(dá)式,以‘#’字符作為結(jié)束標(biāo)志。
Output
輸出該表達(dá)式轉(zhuǎn)換所得到的后綴式。
Sample Input
a*b+(c-d/e)*f#
Sample Output
ab*cde/-f*+
在做這道題之前首先要了解什么是后綴表達(dá)式
百度百科—后綴表達(dá)式
這是一種適合計算機(jī)計算的表達(dá)式,具體步驟:
引用自 Casionx 的CSDN 博客——原表達(dá)式轉(zhuǎn)換為后綴表達(dá)式
附上代碼:
非線性
線性
#include <stdio.h> #include <stdlib.h> #include <string.h>typedef struct stack {char *top,*base;int len; }Stack;Stack newstack() {Stack t;t.top = (char *)malloc(100050*sizeof(char));t.base = t.top;t.len = 0;return t; }char top(Stack t) {return *(t.top-1); }void pop(Stack *t) {t->top--;t->len--; }void push(Stack *t,char x) {*(t->top) = x;t->top++;t->len++; }int judge(char a,char b) {if(b=='(')return 1;if(a=='*'||a=='/'){if(b=='+'||b=='-')return 1;}return 0; }int main() {Stack t;char s[100050],s2[100050];int num = 0,i;t = newstack();scanf("%s",s);for(i=0;s[i]!='#';i++){if(s[i]=='(')push(&t,s[i]);else if(s[i]==')'){while(top(t)!='('){s2[num++] = top(t);pop(&t);}pop(&t);}else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){if(!t.len)push(&t,s[i]);else{while(t.len&&!judge(s[i],top(t))){s2[num++] = top(t);pop(&t);}push(&t,s[i]);}}elses2[num++] = s[i];}while(t.len){s2[num++] = top(t);pop(&t);}s2[num] = '\0';printf("%s\n",s2);return 0; }轉(zhuǎn)載于:https://www.cnblogs.com/luoxiaoyi/p/9747948.html
總結(jié)
以上是生活随笔為你收集整理的SDUT-2132_数据结构实验之栈与队列二:一般算术表达式转换成后缀式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深入理解volatile
- 下一篇: 在多台机器上搭建Hadoop的分布式环境