Question: Please note!! This is only one question, I explained the question in the detailed format with instructions and exmple, you only have edit the given
Please note!! This is only one question, I explained the question in the detailed format with instructions and exmple, you only have edit the given code. Thank you!!
For example, these are balanced expressions:
<({})>
({<>(){}})
But these are not:
({)
<<>[<()>]
Write a C program using structs and pointers to build a stack data structure, and use that stack to check whether a string is properly balanced. Your program should take as a command line input the path to an input file:
./balanced tests/test0.txt
Your program should check whether the expression in the input file is balanced, and then print to the command line "yes" if the expression is balanced, and "no" if it is not.
Below is the given C program to edit:
| #include | |
| #include | |
| #include | |
| // Struct to hold the open and close braces and the pointer to the next element. | |
| struct element { | |
| // char open; // not needed | |
| char close; | |
| struct element* next; | |
| }; | |
| // Append the new element to the start of the stack | |
| // This is one potential way to write this function signature | |
| struct element* push ( | |
| struct element* stack, | |
| // char open, // not needed | |
| char close | |
| ) { | |
| /* ... */ | |
| } | |
| // Remove element from the top of the stack | |
| char pop ( struct element** stack ) { | |
| if (*stack != NULL) { | |
| /* ... */ | |
| } else { | |
| return '\0'; | |
| } | |
| } | |
| int main(int argc, char* argv[]) { | |
| FILE* fp = fopen(argv[1], "r"); | |
| if (!fp) { | |
| perror("fopen failed"); | |
| return EXIT_FAILURE; | |
| } | |
| struct element* root = NULL; | |
| bool balanced = true; | |
| char buff; | |
| while ( fscanf(fp, "%c", &buff)==1 ) { | |
| switch(buff) { | |
| case '<' : | |
| /* ... */ | |
| case '(' : | |
| /* ... */ | |
| case '[' : | |
| /* ... */ | |
| case '{' : | |
| /* ... */ | |
| case '>' : | |
| /* ... */ | |
| case ')' : | |
| /* ... */ | |
| case ']' : | |
| /* ... */ | |
| case '}' : | |
| /* ... */ | |
| default : | |
| printf("Invalid character " ); | |
| } | |
| } | |
| /* ... */ | |
| printf ( balanced ? "yes" : "no" ); | |
| fclose(fp); | |
| return 0; | |
| } |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
