Iterating over linked list in C
Solution 1
How, specifically, to iterate over a linked list depends, to some extent, on its interface.
Not having the interface to the particular implementation you are using available, the question is difficult to answer; but typically; a linked list looks something like this:
typedef struct list_node ListNode;
struct list_node {
void *payload;
ListNode *next;
}
Iterating is usually (always?) done by following the next
pointer, so long as it is not NULL
; like so:
void iterate (ListNode *head) {
while (head) {
if (interested_in_payload(head->payload)) {
// do stuff
}
head = head->next;
}
}
Solution 2
This:
struct node *n = malloc(sizeof(*n));
n = head;
looks very scary. It's almost never correct to first allocate some memory, then immediately overwrite the pointer.
Perhaps you meant
head = n;
?
Related videos on Youtube
user1927323
Updated on June 04, 2022Comments
-
user1927323 almost 2 years
I have a linked list that contains two "strings", one for searching and one for replacing. I also have a text file that I'm supposed to open and read line by line then see if the words exist in the "dictionary" (the linked list) if it does, I have to replace it with the word's definition. Then write the changed text into a new text file, so I thought I should use a buffer when reading.
The problem is, I don't know how to iterate over the linked list. So far I have two words in it but it only searches for the first one in the loop:
char *textLine = NULL; size_t textlen = 0; ssize_t readText; struct node *n = malloc(sizeof(*n)); n = head; char buffer[MAX_L]; while ((readText = getline(&textLine, &textlen, t)) != -1) { char *t = strtok(textLine, " "); while (t != NULL) { if (strcmp(t,n->word) == 0) { // do something } else { // do something } n = head; t = strtok(NULL, " "); } }
head
isNULL
, I guess that's why it only searches for the first word I just don't really know how should I iterate over both the lines and the linked list.-
Frerich Raabe over 10 yearsShouldn't there be some sort of
n = n->next;
assignment or the like within the innerwhile
loop. Instead of just doingn = head;
.
-
-
Williham Totland over 10 yearsNever is a dangerous word. Personally, I'd probably go with "not" for this case, and "very rarely" for the more general concept. (Weird things happen in embedded programming.)
-
unwind over 10 years@WillihamTotland Hm ... yeah, okay, why not, I made it "almost never". :)