-
help with linked list
Hi everyone,
I am building a linked list by merging 2 sorted arrays.
My code is below. now my question is how can I make ptr->name point to list1[i] or list2[j] accroedingly in the if statement?
Thanks,
#include<string.h>
#include <stdio.h>
#define CHARS 30
#define NAMES 20
main()
{
struct NODE {
char name[CHARS];
struct NODE *next;
};
typedef struct NODE Node;
int count= -1;
int i,j,x;
char list1[NAMES][CHARS],list2[NAMES][CHARS];
FILE *fp;
Node* head;
Node* curr;
head=(Node*)malloc(sizeof(Node));
curr=head;
fp=fopen("merge.dat","r");
while (!feof(fp)) {
count++;
fscanf(fp,"%s %s ",list1[count],list2[count]);
}
fclose(fp);
while(i<count && j<count)
{
curr->next=(Node*)malloc(sizeof(Node));
curr=curr->next;
if(strcmp(list1[i],list2[j])<0)
{
curr->name=list1[i];//THIS IS THE PART THAT I HAVE A ? ON.
j++;
}
else
{
curr->name=list2[j];
i++;
}
}
if (i=count-1)
for(x=j;x<count;x++)
{
curr->next=(Node*)malloc(sizeof(Node));
curr=curr->next;
curr->name=list2[x];
}
else
for(x=i;x<count;x++)
{
curr->next=(Node*)malloc(sizeof(Node));
curr=curr->next;
curr->name=list1[x];
}
}
-
Umm, you are doing that in your program.
curr->name = list[x];
This means that you are making curr->name point to the x'th
element of list, which is a char*(or string).
Or maybe i just don't understand what you want to do!!
-
A few pointers for you...
>head = (Node *) malloc(sizeof(Node));
>fp = fopen("merge.dat", "r");
I presume this a test program, but even so, you should error check both of these functions before they give you a headache.
Also, the cast on malloc() isn't necessary.
>while (!feof(fp))
This is an incorrect use of feof(). It might not give you the results you expect. You should check the return code from fscanf() instead.
>fscanf(fp, "%s %s ", list1[count], list2[count]);
What if there are too many lines in the file to fit in the buffer? You need to check this, or you will cause an overflow.
>while (i < count && j < count)
Both i and j are uninitialised at this point, meaning you have no idea what their values are the first time through the loop.
I'm not too sure where your heading with your linked list code, so the best advice I can give is have a read of these pages for plenty of example code on this topic.
Hope this helps :)