0% found this document useful (0 votes)
11 views

DSA 13

Uploaded by

Ayush Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

DSA 13

Uploaded by

Ayush Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Program-13

Program to demonstrate the use of stack in evaluating arithmetic expression in postfix


notation.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Node structure for the linked list
struct Node {
int data;
struct Node* next;
};

// Structure to represent a stack using a linked list


struct Stack {
struct Node* top;
};

// Function to initialize the stack


void initialize(struct Stack* s) {
s->top = NULL;
}

// Function to check if the stack is empty


int isEmpty(struct Stack* s) {
return s->top == NULL;
}

// Function to push an element onto the stack


void push(struct Stack* s, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}

newNode->data = value;
newNode->next = s->top;
s->top = newNode;
}
// Function to pop an element from the stack
int pop(struct Stack* s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
int value = s->top->data;
struct Node* temp = s->top;
s->top = s->top->next;
free(temp);

return value;
}
// Function to evaluate an arithmetic expression in postfix notation
int evaluatePostfix(char postfix[]) {
struct Stack stack;
initialize(&stack);
int i, operand1, operand2, result;
char ch;
for (i = 0; postfix[i] != '\0'; i++) {
ch = postfix[i];
if (isdigit(ch)) {
push(&stack, ch - '0'); // Convert character to integer and push onto the stack
} else {
operand2 = pop(&stack);
operand1 = pop(&stack);
switch (ch) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 != 0) {
result = operand1 / operand2;
} else {
printf("Division by zero\n");
exit(EXIT_FAILURE);
}
break;
default:
printf("Invalid operator\n");
exit(EXIT_FAILURE);
}
push(&stack, result);
}
}
if (!isEmpty(&stack)) {
result = pop(&stack);
if (isEmpty(&stack)) {
return result;
} else {
printf("Invalid expression\n");
exit(EXIT_FAILURE);
}
} else {
printf("Invalid expression\n");
exit(EXIT_FAILURE);
}
}
int main() {
char postfix[100];
printf("Name :- Varun\nRoll no.- 221901258\n");
printf("Enter a postfix expression: ");
gets(postfix);
int result = evaluatePostfix(postfix);
printf("Result: %d\n", result);

return 0;
}

Output:

You might also like