|
|
 |
|
 |
|
|
C++ Language Tutorial Page 11
Advanced Structures
Bjorfck Silas
Previous Index Next
A linked list is essentially a dynamic array made of structures. Because of its struct-essence, it possesses properties which rival those of mere arrays!
These I will show thee. First, a basic linked-list node, containing an int of data:
struct node{
int data;
struct node *next;
};
Now, this is rather simple to understand. The weird bit, *next, is a pointer to the next node. The linked list is navigated by following these references.
For instance, a simple routine to find a phone # in a linked list of people would look something like this:
//first, the node struct
struct node{
int age;
int phone;
char name[20];
node *next;
}
//all linked-lists are usually defined solely by a pointer to the first element.
struct list{
node *first;
}
//the function takes a struct list and a string specifying a name(up to 20 chars), and returns the phone-number. If it can't find it, it returns -1.
int getphone(struct list target_list,char name[20]){
struct node *i;
for(i = target_list.first;i->next != NULL;i = i->next){
if(i->name == name)
return i->phone;
}
return -1;
}
|
|
|
|
|
|