saner
saner

Reputation: 438

Iterate a linked list

Let's say we have

typedef struct Node{
int num;
struct Node *next;
} node;

node *next1 = NULL;
node node1 = {1, &next1};
node *next0 = &node1;
node node0 = {0, &next0};
node *start = &node0;

Why does the following not work to iterate over it (we get into an infinite loop)?

node *p = start;
while (p != NULL){p = p->next; }

Upvotes: 2

Views: 72

Answers (3)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5601

First of all learn bit more about link list. Your list creation codes are totally wrong. Read my comment in below code to understand your mistakes:-

node *node1 = {1, NULL};//or {1,NULL} not the address of pointer, next1 is pointing to NULL, here you have created the first node
//node *next0 = &node1;// what are you doing here and what are you doing below
//node node0 = {0, &next0};//wrong
node node0 = {0, NULL};// here you have created the second node
node *start = &node0;// you have assign the address of second node to start

//you need to join both the nodes to make it a list
start->next = node1; 

Also you can implement like below:-

node *node1 = {1, NULL};//create first node here
node *next0 = {0, node1};//create second node and link to first node already created in above code
node *start = node0;// now start is pointing to the first node of the list

Now below code will work.

  node *p = start;
  while (p != NULL){p = p->next; }

Upvotes: 1

Achal
Achal

Reputation: 11931

problem is in the below statement

node node1 = {1, &next1}; /* node1 next field should be next1 not &next1 */

It should be

node node1 = {1, (struct Node*)next1}; /* similarly for node0 */

Here is the working code

#include<stdio.h>
int main() {
        typedef struct Node{
                int num;
                struct Node *next;
        } node;

        node *next1 = NULL;
        node node1 = {1, (struct Node*)next1};
        node *next0 = &node1;
        node node0 = {0, (struct Node*)next0};
        node *start = &node0;

        node *p = start;
        while (p != NULL){
                printf("%d \n",p->num);
                p = p->next;
        }
   }   

Upvotes: 3

hafeez
hafeez

Reputation: 169

Try to use this instead of your confusing declarations.

node node1 = {1, NULL};
node node0 = {0, &node1};
node *start = &node0;

This works for me.

Upvotes: 2

Related Questions