|
LINKED LISTSA linked
list is a chain of structs or records called nodes. Each node has at
least two members, one of which points to the next item or node in
the list! These are defined as Single Linked Lists because they only
point to the next item, and not the previous. Those that do point to
both are called Double Linked Lists.
-------- --------
| data | --->| data |
|--------| | |--------|
| pointer|---- | pointer| ---> NULL
-------- --------
A structure which contains a data element and a pointer to the next
node is created by,
struct list {
int value;
struct list *next;
};
This defines a new data structure called list (actually the
definition of a node), which contains two members. The first is an
integer called value. The second is called next, which is a pointer
to another list structure (or node). Suppose that we declare two
structures to be of the same type as list, eg,
struct list n1, n2;
The next pointer of structure n1 may be set to point to the n2
structure by
/* assign address of first element in n2 to the pointer next of the
n1 structure */
n1.next = &n2;
which creates a link between the two structures.
Example to Illustrate linked lists
#include <stdio.h>
struct list {
int value;
struct list *next;
};
main()
{
struct list n1, n2, n3;
int i;
n1.value = 100;
n2.value = 200;
n3.value = 300;
n1.next = &n2;
n2.next = &n3;
i = n1.next->value;
printf("%d\n", n2.next->value);
}
|
|