Using a linked stack, write a program that will read a text file containing an a
ID: 3532359 • Letter: U
Question
Using a linked stack, write a program that will read a text file containing an arbitrary sequence of characters, some of which might be <>, [], {}, and ().Echo the characters to the console as they are read, but stop at a mismatching character, with the indication Using a linked stack, write a program that will read a text file containing an arbitrary sequence of characters, some of which might be <>, [], {}, and ().
Echo the characters to the console as they are read, but stop at a mismatching character, with the indication
Explanation / Answer
This is a perfectly working code on g++ compiler.
I have did an exhaustive testing on it. It is in C++ so please rate 5.
#include <cstdio>
#include <cstdlib>
#include <string>
typedef struct STACK{
char a;
struct STACK* next;
}stack;
int main()
{
char file[100];
printf("Enter the file name: ");
scanf("%s",file);
FILE* fp = fopen(file,"r");
stack* head=NULL,*tail=NULL,*node=NULL;
char c;
while(fscanf(fp,"%c",&c) != EOF)
{
if(c == '<' || c=='(' || c=='{' || c=='[')
{
if(tail == NULL)
{
tail = (stack*)malloc(sizeof(stack));
tail->a = c;
tail->next = NULL;
head = tail;
}
else
{
node= (stack*)malloc(sizeof(stack));
node->a = c;
node->next = NULL;
tail->next = node;
tail=tail->next;
}
}
if(c == '>' || c==')' || c=='}' || c==']')
{
if(!((tail->a == '(' && c == ')') || (c - tail->a) == 2))
{
printf("Mismatched (%c) ",tail->a);
return 0;
}
else
{
tail = head;
if(tail->next != NULL)
{
while(tail->next->next != NULL)
tail=tail->next;
tail->next = NULL;
}
else
{
tail = NULL;
head = NULL;
}
}
}
}
printf("Matched ");
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.