Nhờ mọi người xem giúp code này sai ở đâu để em sửa. Em xin cảm ơn !.
#include <conio.h>
#include <string>
using namespace std;
struct Node{
string data;
struct Node *pNext;
};
typedef struct Node NODE;
struct Stack{
NODE *pTop;
};
typedef struct Stack STACK;
// Khởi tạo Stack
void InitStack(STACK &stack){
stack.pTop = NULL;
}
// Kiểm tra Stack có rỗng hay không
bool IsEmpty(STACK &stack){
if (stack.pTop == NULL)
{
return false;
}
return true;
}
// Tạo Node
NODE* GetNode(string x){
NODE *newNode = new NODE;
newNode->data = x;
newNode->pNext = NULL;
return newNode;
}
// Đặt Node vào trong Stack
void Push(STACK &stack, NODE *p){
if (IsEmpty(stack) == false){
stack.pTop = p;
}
else{
p->pNext = stack.pTop;
stack.pTop = p;
}
}
// Lấy Node ra khỏi Stack
string Pop(STACK &stack)
{
string x;
NODE *p = stack.pTop; // Con trỏ p trỏ tới con trỏ Top.
x = p->data;
stack.pTop = stack.pTop->pNext;
delete p;
return x;
}
// Xem phần tử đầu của Stack
void Top(STACK stack){
if (IsEmpty(stack) == false){
cout << "Stack rong~ !";
system("pause");
return;
}
else{
string x;
x = stack.pTop->data;
cout << x;
}
}
// Hàm nhập
void Input(STACK &stack){
string str;
cout << "Moi ban nhap bieu thuc:";
getline(cin, str);
InitStack(stack);
string p1, p2, p3;
int ketQua;
for (int i = 0; i < str.length(); i++){
NODE *p = new NODE;
// TH1
if (str[i] = '('){
continue;
}
// TH2
string temp;
int start, end;
if (str[i] >= '0' && str[i] <= '9'){
start = i;
for (int j = i + 1; j < str.length(); j++){
if (str[j] < '0' || str[j] '9'){
end = j;
i = j;
break;
}
}
end - 1;
temp = str.substr(start, end - start);
p = GetNode(temp);
Push(stack, p);
}
// TH3
if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/'){
char *temp = new char;
temp[0] = str[i];
temp[1] = '\0';
string a = temp;
p = GetNode(a);
Push(stack, p);
}
if (str[i] == ')'){
p1 = Pop(stack);
p2 = Pop(stack);
p3 = Pop(stack);
int num3, num1;
num3 = atoi(p3.c_str());
num1 = atoi(p1.c_str());
if (p2 == "+"){
ketQua = num3 + num1;
}
else if (p2 == "-"){
ketQua = num3 - num1;
}
else if (p2 == "*"){
ketQua = num3 * num1;
}
else if (p2 == "/"){
ketQua = num3 / num1;
};
char chr[20];
itoa(ketQua, chr, 10);
NODE *q = GetNode((string)chr);
Push(stack, q);
}
}
}
// Hàm in ra kết quả
void Output(STACK &stack){
while (IsEmpty(stack) == true){
string str;
str = Pop(stack);
cout << str;
}
}
int main(){
STACK stack;
Input(stack);
Output(stack);
system("pause");
return 0;
}
Ví dụ biểu thức nhập vào là (12 + 3) thì nó sẽ in ra là 15.