Upload files to "DS/C/Lab/Week5"
This commit is contained in:
parent
44cced8454
commit
5b8ed261ff
3 changed files with 96 additions and 56 deletions
|
@ -6,61 +6,80 @@
|
|||
int stack[MAX_SIZE];
|
||||
int top = -1;
|
||||
|
||||
void push(int item) {
|
||||
if (top >= MAX_SIZE - 1) {
|
||||
void push(int item)
|
||||
{
|
||||
if (top >= MAX_SIZE - 1)
|
||||
{
|
||||
printf("Stack Overflow\n");
|
||||
return;
|
||||
}
|
||||
stack[++top] = item;
|
||||
}
|
||||
|
||||
int pop() {
|
||||
if (top < 0) {
|
||||
int pop()
|
||||
{
|
||||
if (top < 0)
|
||||
{
|
||||
printf("Stack Underflow\n");
|
||||
return -1; // Return a sentinel value instead of exiting
|
||||
return -1;
|
||||
}
|
||||
return stack[top--];
|
||||
}
|
||||
|
||||
int isDigit(char c) {
|
||||
int isDigit(char c)
|
||||
{
|
||||
return c >= '0' && c <= '9';
|
||||
}
|
||||
|
||||
int evaluatePostfix(char* exp) {
|
||||
int evaluatePostfix(char *exp)
|
||||
{
|
||||
int i, operand1, operand2, result;
|
||||
|
||||
for (i = 0; exp[i] != '\0'; i++) {
|
||||
if (isDigit(exp[i])) {
|
||||
|
||||
for (i = 0; exp[i] != '\0'; i++)
|
||||
{
|
||||
if (isDigit(exp[i]))
|
||||
{
|
||||
push(exp[i] - '0');
|
||||
} else {
|
||||
}
|
||||
else
|
||||
{
|
||||
operand2 = pop();
|
||||
operand1 = pop();
|
||||
switch (exp[i]) {
|
||||
case '+': push(operand1 + operand2); break;
|
||||
case '-': push(operand1 - operand2); break;
|
||||
case '*': push(operand1 * operand2); break;
|
||||
case '/':
|
||||
if (operand2 == 0) {
|
||||
printf("Error: Division by zero\n");
|
||||
return -1; // Return a sentinel value instead of exiting
|
||||
}
|
||||
push(operand1 / operand2);
|
||||
break;
|
||||
switch (exp[i])
|
||||
{
|
||||
case '+':
|
||||
push(operand1 + operand2);
|
||||
break;
|
||||
case '-':
|
||||
push(operand1 - operand2);
|
||||
break;
|
||||
case '*':
|
||||
push(operand1 * operand2);
|
||||
break;
|
||||
case '/':
|
||||
if (operand2 == 0)
|
||||
{
|
||||
printf("Error: Division by zero\n");
|
||||
return -1;
|
||||
}
|
||||
push(operand1 / operand2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return pop();
|
||||
}
|
||||
|
||||
int main() {
|
||||
int main()
|
||||
{
|
||||
char exp[MAX_SIZE];
|
||||
printf("Enter a postfix expression: ");
|
||||
fgets(exp, MAX_SIZE, stdin);
|
||||
exp[strcspn(exp, "\n")] = 0; // Remove newline if present
|
||||
|
||||
gets(exp);
|
||||
|
||||
int result = evaluatePostfix(exp);
|
||||
if (result != -1) {
|
||||
if (result != -1)
|
||||
{
|
||||
printf("Result: %d\n", result);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue