-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04_Stack.cpp
128 lines (108 loc) · 2.75 KB
/
04_Stack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int value) {
data = value;
next = nullptr;
}
};
class Stack {
public:
Node* head = nullptr;
void push(int value) {
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
}
void pop() {
if (head == nullptr) {
cout << "Stack is empty" << endl;
return;
}
Node* temp = head;
head = head->next;
delete temp;
}
int top() {
if (head == nullptr) {
cout << "Stack is empty" << endl;
return -1;
} else {
return head->data;
}
}
bool isEmpty() {
return head == nullptr;
}
void display() {
if (head == nullptr) {
cout << "Stack is empty" << endl;
return;
}
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int evaluatePostfix(const string& expression) {
Stack stack;
istringstream iss(expression);
string token;
while (iss >> token) {
if (isdigit(token[0])) {
stack.push(stoi(token));
} else {
int b = stack.top(); stack.pop();
int a = stack.top(); stack.pop();
switch (token[0]) {
case '+': stack.push(a + b); break;
case '-': stack.push(a - b); break;
case '*': stack.push(a * b); break;
case '/': stack.push(a / b); break;
}
}
}
return stack.top();
}
int evaluatePrefix(const string& expression) {
Stack stack;
istringstream iss(expression);
vector<string> tokens;
string token;
while (iss >> token) {
tokens.push_back(token);
}
reverse(tokens.begin(), tokens.end());
for (const auto& tok : tokens) {
if (isdigit(tok[0])) {
stack.push(stoi(tok));
} else {
int a = stack.top(); stack.pop();
int b = stack.top(); stack.pop();
switch (tok[0]) {
case '+': stack.push(a + b); break;
case '-': stack.push(a - b); break;
case '*': stack.push(a * b); break;
case '/': stack.push(a / b); break;
}
}
}
return stack.top();
}
int main() {
string postfix = "5 6 + 4 *";
string prefix = "* + 5 6 4";
cout << "Postfix Evaluation: " << evaluatePostfix(postfix) << endl;
cout << "Prefix Evaluation: " << evaluatePrefix(prefix) << endl;
return 0;
}