Reputation: 31
This is part of a larger bit of code but I will include what I think is important. There are actually two types of linked lists I am working with. As you will see the first struct just links to the first node of the list.
Here's the first:
typedef struct mlist {
Node *headFirstName;
Node *headLastName;
} MultiLinkedList;
Here's the second:
typedef struct node {
char *first;
char *last;
long number;
struct node *nextFirst;
struct node *nextLast;
} Node;
Here is how names and numbers are currently added to the list:
MultiLinkedList *add(MultiLinkedList *list, char *first, char *last, long num) {
// allocate a new node
Node *newNode = malloc ( sizeof(Node) );
newNode->first = malloc ( strlen(first) + 1 );
strcpy(newNode->first, first);
newNode->last = malloc ( strlen(last) + 1 );
strcpy(newNode->last, last);
newNode->number = num;
// add this new node at the head of the "byFirst" list
newNode->nextFirst = list->headFirstName;
list->headFirstName = newNode;
// add this new node at the head of the "byLast" list
newNode->nextLast = list->headLastName;
list->headLastName = newNode;
// return the multi-list object with updated head pointers
return list;
}
And here is how I am currently attempting to count the names in the list:
int size(MultiLinkedList *list) {
int count = 0;
Node *newNode = malloc ( sizeof(Node) );
newNode->nextFirst = list->headFirstName;
newNode->nextLast = list->headLastName;
while (newNode->nextFirst!=NULL) {
count++;
}
// return the number of names in the list
return count;
}
If there is a specific name for traversing multiple lists like this then could someone just direct me to that?
Upvotes: 0
Views: 54
Reputation: 26747
size_t
for sizemalloc()
is uselessx = x->next
how do you want your loop finish ?size_t size(MultiLinkedList *list) {
size_t count = 0;
for (Node *i = list->headFirstName; i; i = i->next) {
count++;
}
// return the number of names in the list
return count;
}
Upvotes: 1