Reputation: 169
Ok so I have the following code:
typedef struct node {
char line[3];
struct node* next;
}NODE;
NODE * enq(char b[]);
NODE * deq(NODE *head);
void printQueue (NODE *head);
int main(void)
{
FILE* fp;
char* filename = "expressions.txt";
char buffer[50];
int len;
struct node *head = NULL, *tail, *temp, *temp2;
if((fp=fopen(filename, "r"))==NULL)
{
printf("unable to open %s\n", filename);
exit(1);
}
while(fgets(buffer, sizeof(buffer), fp) !=NULL)
{
len=strlen(buffer);
if(buffer[len-1]=='\n')
buffer[len-1]='\0';
if (strcmp("=",buffer) ==0)
{
printQueue(head);
}
else
{
temp = enq(buffer);
if(head ==NULL)
head = temp;
else
tail->next = temp;
tail = temp;
}
}
}
NODE * enq(char b[])
{
NODE *temp = malloc(sizeof(NODE));
strcpy(temp->line, b);
temp -> next = NULL;
return temp;
}
NODE *deq(NODE *head)
{
NODE *temp = head->next;
free(head);
return temp;
}
void printQueue (NODE *head)
{
char hold[3];
int sum = 0, place, sign;
while(head !=NULL)
{
strcpy(hold, head->line);
if(hold[0] < 58 && hold[0]>47)
{
place = atoi(hold);
if (sign == -1)
{
place = place *sign;
sign = 1;
}
sum = sum + place;
}
else if (strcmp(hold, "-")==0)
{
sign = -1;
}
printf("%s ", hold);
head=deq(head);
}
printf("= %d\n",sum);
}
This is my input data from the file:
71
-
67
-
71
+
9
-
19
=
27
+
8
+
10
-
94
-
64
=
The expected output is this:
71 - 67 - 71 + 9 - 19 = -77
27 + 8 + 10 - 94 - 64 = -113
Output I am getting:
71 - 67 - 71 + 9 - 19 = -77
64 = 64
It always does the first set of expressions correctly, any expression after that, it skips some of the elements in the linked list, now I THINK I have narrowed it down to the dequeue method, that is not working correctly when I am freeing head. If I don't free and just test the print output, it prints out every single element in the list which is ok for observations but at the end of the day, I need to free each node as I extract it from the list and I am not sure why it is skipping a whole bunch of nodes. I printed the list before it is sent to printQueue and it seems fine, but right after dequeueing, the elements start to disappear. Any insight would be helpful.
Upvotes: 0
Views: 139
Reputation: 121
This happens because you forget to reset the head pointer after you printed the result of an expression and are starting to parse a new expression (hence, a new linked list).
In your main(), try to replace the snippet
if (strcmp("=",buffer) ==0)
{
printQueue(head);
}
by
if (strcmp("=",buffer) ==0)
{
printQueue(head);
head = NULL;
}
And you should get the expected output.
Please also beware of the memory leak that would happen if your input file does not end by a '=' (this would not call your printQueue() in which you currently free your list nodes).
Upvotes: 2