user1927323
user1927323

Reputation: 25

Iterating over linked list in C

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 is NULL, 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.

Upvotes: 2

Views: 14065

Answers (2)

unwind
unwind

Reputation: 399833

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;

?

Upvotes: 1

Williham Totland
Williham Totland

Reputation: 29009

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;
  }
}

Upvotes: 4

Related Questions