#include <iostream>
#include<cctype>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct Node
{
int data;
Node* next;
};
class Stack
{
private:
Node* top;
public:
Stack()
{
top = NULL;
}
~Stack();
void Push(int Elem);//入堆疊
int Pop();//出堆疊,回傳值型別
int Top();//回傳堆疊頂元素
};
Stack::~Stack()//解構式,清空堆疊
{
Node* p;
while (top)
{
p = top->next;
delete top;
top = p;
}
cout << "堆疊已清空" << endl;
}
int Stack::Pop()
{
if (top == NULL)
{
cout << "堆疊為空" << endl;
return -1;
}
else
{
Node* p;
int a;
a = top->data;
p = top;
top = top->next;
delete p;
return a;
}
}
void Stack::Push(int Elem)//入堆疊操作
{
Node* s;
s = new Node;
s->data=https://bbs.csdn.net/topics/ Elem;
s->next = top;
top = s;
}
int Stack::Top()
{
return top->data;
}
int main()//主函式
{
Stack st;
char string[10];
int i=0 ;
cin >> string[0];
while (string[i] != '#')
{
if (isdigit(string[i]))
{
st.Push(string[i]);
}
else
{
int a, b, result;
switch (string[i])
{
case'+':
a = st.Pop();
b = st.Pop();
result = a + b;
st.Push(result);
break;
case'-':
a = st.Pop();
b = st.Pop();//先彈出的為第二運算元
result = b-a;
st.Push(result);
break;
case'*':
a = st.Pop();
b = st.Pop();
result = a* b;
st.Push(result);
break;
case'/':
a = st.Pop();
b = st.Pop();
if (a == 0)
{
cout << "error" << endl;
}
else
{
result = b / a;
st.Push(result);
}
}
}
i++;
cin >> string[i];
}
cout << st.Top()<<endl;
return 0;
}
uj5u.com熱心網友回復:
輸入的運算式沒有括號嗎uj5u.com熱心網友回復:
我輸入的 2 3 * #{以#號結束)結果應該是6,但控制臺輸出的卻是2550
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/269146.html
標籤:新手樂園
上一篇:各位大神,誰有arcgis的加權泰森多邊形(V圖)插件,萬分感謝啊,[email protected]
下一篇:求教c++中如何使用字串
