Liên kết đơn - Linked List, bài 2

How to set up a linked list
typedef struct list_item {
information in each item
struct list_item *nextptr;
} LIST_ITEM;


 
Address book with linked lists
typedef struct list {
char name[MAXLEN];
char address[MAXLEN];
char phone[MAXLEN];
struct list *next;
} ADDRESS;
ADDRESS *hol= NULL;
/* Set the head of the list */


 Creating a New Node
• Allocate space for a new node.
• Set the next pointer to the value of NULL
• Set the data value for the node.


Adding Nodes to the List
• If the start node is null then the start node
becomes the new node.
• If start is not null then start becomes the
new node‟s next and the start becomes the
new node.


Adding to our address book
void add_to_list (void)
/* Add a new name to our address book */
{
ADDRESS *new_name;
new_name= (ADDRESS *)malloc (sizeof (ADDRESS));
/* CHECK THE MEMORY! */
printf ("Name> ");
fgets (new_name->name, MAXLEN, stdin);
printf ("Address> ");
fgets (new_name->address, MAXLEN, stdin);
printf ("Tel> ");
fgets (new_name->phone, MAXLEN, stdin);
/* Chain the new item into the list */
new_name->next= hol;
hol= new_name;


Search in the Address Book
ADDRESS * search (char *name)
/* look for a particular name in our address book */
{
ADDRESS *p = hol;
while(p != NULL && !strcmp(p->name, name))
{
p = p->next;
}
return p;
}


Delete in the Address Book
void delete(char *name)
/* delete a particular name in our address book */
{
ADDRESS *p = hol;
ADDRESS *q = hol;
if(hol != NULL && strcmp(hol->name, name))
{
hol = hol->next;
p->next = NULL;
free(p);
}
else
{
while(p != NULL && !strcmp(p->name, name))
{
q = p;
p = p->next;
}
q->next = p->next;
p->next = NULL;
free(p);
}
}