Tuesday, 25 June 2013

The simplest way to iterate a linked list

The easiest way to iterate through a linked list in C or Java is with a for loop. The code is as simple as this:

C:

typedef struct _nd {
  struct _nd * next;
  char val[10];
} Node;

Node * i;
for (i=root; i; i=i->next) {
  printf("%s", i->val);
}

Java:

class Node {
  Node next;
  String val;
}

for (Node i=root; i!=null; i=i->next) {
  System.out.println(i.val);
}


No comments:

Post a Comment