Repository navigation
Expand file tree
/
Copy pathstackLinkedList
More file actions
164 lines (158 loc) · 2.46 KB
/
Copy pathstackLinkedList
File metadata and controls
164 lines (158 loc) · 2.46 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#include <stdio.h>
#include <stdlib.h>
struct Stack
{
int data;
struct Stack *next;
} * Top = NULL;
void push(int x)
{
struct Stack *t = (struct Stack *) malloc(sizeof(Struct Stack));
if (!t ) return;
t->data = x;
t->next = Top;
Top = t;
}
int pop()
{
x = -1;
struct Stack *t;
if ( !isEmpty(st) ) {
t = Top;
Top = Top->next;
x = t->data;
free(t);
}
return x;
}
int peak(int pos)
{
struct Stack *t;
t = Top;
for ( int i = 0; i < pos-1 && t; i++) {
t = t->next;
}
if ( t ) {
return t->data;
} else {
return -1;
}
}
class Node
{
public:
int data;
Node *next;
}
using namespace std;
class Stack
{
private:
Node * top;
public:
Stack() { top = NULL; }
~Stack() {};
void push(int x);
int pop();
void Display();
}
void Stack::push(int x)
{
Node * t = nex Stack();
if ( !t ) {
cout << "Stack is full"
} else {
t->data = x;
t->next = top;
top = t;
}
}
int Stack::pop()
{
Node *t;
int x = -1;
if (!top) {
cout << "Stack is empty\n";
} else {
t = top;
top = top->next;
x = t->data;
delete t;
}
return x;
}
void Stack::Display()
{
Node *t = top;
while(t) {
cout << t->data << " ";
t = t->next;
}
cout << endl;
}
char * convert(char *infix)
{
char *post = (char *) malloc(sizeof(char) * (strlen(infix) + 1));
Stack stk;
int i = 0; j = 0;
while (infix[i] != '\0') {
if(isOperand(infix[i]) ) {
post[j++] = infix[i++];
} else {
if ( stk.isEmpty() || preference(infix[i]) > preference(stk.top()) {
stk.push(infix[i++]);
} else {
post[j++] = stk.pop();
}
}
}
while( !stk.isEmpty()){
post[j++] = stk.pop();
}
post[j] = '\0';
return post;
}
int Eval(char * post)
{
Stack<int> stk;
int val = 0;
int i = 0;
int right, left, res;
while (post[i] != '\0') {
if ( isOperand(post[i]) ) {
stk.push(post[i++]-'0');
} else {
right = stk.pop();
left = stk.pop();
switch(post[i]) {
case '+':
res = left + right;
break;
case '-' :
res = left - right;
break;
case '*':
res = left * right;
break;
case '/':
res = left / right;
break;
default:
break;
}
stk.push(res);
i++;
}
}
return stk.top();
}
int main()
{
Stack stk;
stk.push(1);
stk.push(2);
stk.pop();
stk.pop();
stk.Display();
return 1;
}