forked from Septchi/CS_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfixL.c
More file actions
99 lines (88 loc) · 1.96 KB
/
Copy pathpostfixL.c
File metadata and controls
99 lines (88 loc) · 1.96 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
#include <ctype.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct node* nodeptr;
struct node{
int val;
nodeptr next;
};
int pop(nodeptr* head){
int data = (*head)->val;
nodeptr temp = *head;
*head = temp->next;
free(temp);
return data;
}
void push(nodeptr* head, int data){
nodeptr node = malloc(sizeof(nodeptr));
node->val = data;
node->next = *head;
*head = node;
}
bool isEmpty(nodeptr head){
bool empty = false;
if(head == NULL)
empty = true;
return empty;
}
int main(){
char input[16];
printf("enter postfix equation: ");
fgets(input, 16, stdin);
bool empty;
char op;
int i = 0;
float n1, n2, res;
nodeptr head = NULL;
while((op = input[i++]) != '\n'){
printf("op: %c\n", op);
if(isdigit(op)){
res = op - '0';
push(&head, res);
}
else{
empty = isEmpty(head);
if(!empty)
n1 = pop(&head);
else{
printf("stack empty\n");
return 0;
}
empty = isEmpty(head);
if(!empty)
n2 = pop(&head);
else{
printf("stack empty\n");
return 0;
}
switch(op){
case '+':
res = n1 + n2;
break;
case '-':
res = n2 - n1;
break;
case '*':
res = n1 * n2;
break;
case '/':
res = n2 / n1;
break;
}
push(&head, res);
}
}
empty = isEmpty(head);
if(!empty)
res = pop(&head);
else{
printf("stack empty\n");
return 0;
}
empty = isEmpty(head);
if(empty)
printf("Result is %.2f\n", res);
else
printf("Error");
}