Upload files to "DS/C/Lab/Week6"
This commit is contained in:
parent
0cdc830d54
commit
c6df50662d
4 changed files with 287 additions and 0 deletions
63
DS/C/Lab/Week6/PrefixToPostfix.c
Normal file
63
DS/C/Lab/Week6/PrefixToPostfix.c
Normal file
|
@ -0,0 +1,63 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_SIZE 100
|
||||
|
||||
char stack[MAX_SIZE][MAX_SIZE];
|
||||
int top = -1;
|
||||
|
||||
void push(const char* item) {
|
||||
if (top >= MAX_SIZE - 1) {
|
||||
printf("Stack Overflow\n");
|
||||
return;
|
||||
}
|
||||
strcpy(stack[++top], item);
|
||||
}
|
||||
|
||||
char* pop() {
|
||||
if (top < 0) {
|
||||
printf("Stack Underflow\n");
|
||||
return NULL;
|
||||
}
|
||||
return stack[top--];
|
||||
}
|
||||
|
||||
int isOperator(char c) {
|
||||
return (c == '+' || c == '-' || c == '*' || c == '/');
|
||||
}
|
||||
|
||||
int isAlphanumeric(char c) {
|
||||
return ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
|
||||
}
|
||||
|
||||
void prefixToPostfix(char* prefix) {
|
||||
int len = strlen(prefix);
|
||||
char temp[MAX_SIZE];
|
||||
|
||||
for (int i = len - 1; i >= 0; i--) {
|
||||
if (isAlphanumeric(prefix[i])) {
|
||||
temp[0] = prefix[i];
|
||||
temp[1] = '\0';
|
||||
push(temp);
|
||||
} else if (isOperator(prefix[i])) {
|
||||
char op1[MAX_SIZE], op2[MAX_SIZE], result[MAX_SIZE];
|
||||
strcpy(op1, pop());
|
||||
strcpy(op2, pop());
|
||||
sprintf(result, "%s%s%c", op1, op2, prefix[i]);
|
||||
push(result);
|
||||
}
|
||||
}
|
||||
|
||||
printf("Postfix expression: %s\n", stack[top]);
|
||||
}
|
||||
|
||||
int main() {
|
||||
char prefix[MAX_SIZE];
|
||||
printf("Enter prefix expression: ");
|
||||
fgets(prefix, MAX_SIZE, stdin);
|
||||
prefix[strcspn(prefix, "\n")] = 0; // Remove newline if present
|
||||
|
||||
prefixToPostfix(prefix);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue