A linked list with header nodes has a fictitious node. The first node in the linked list is actually the second node.
# Include <stdlib. h>
Struct llist
{
Int num;
Struct llist * next;
};
Typedef struct llist node;
Typedef node * llink;
// Output node Value
Void printllist (llink head)
{
Llink ptr;
Ptr = head-> next;
While (ptr! = NULL)
{
Printf ("% d", ptr-> num );
Ptr = ptr-> next;
}
Printf ("");
}
// Find the node
Llink findnode (llink head, int value)
{
Llink ptr;
Ptr = head-> next;
While (ptr! = NULL)
{
If (ptr-> num = value)
{
Return ptr;
}
Ptr = ptr-> next;
}
Return NULL;
}
// Create a linked list
Llink createllist (int * array, int len)
{
Llink head;
Llink ptr, ptr1;
Int I;
Head = (llink) malloc (sizeof (node ));
If (head = NULL)
{
Printf ("memory allocation failed! ");
Return NULL;
}
Ptr = head;
For (I = 0; I <len; I ++)
{
Ptr1 = (llink) malloc (sizeof (node ));
If (! Ptr1)
{
Return NULL;
}
Ptr1-> num = array [I];
Ptr1-> next = NULL;
Ptr-> next = ptr1;
Ptr = ptr1;
}
Return head;
}
// Insert a node
Llink insertnode (llink head, llink ptr, int nodevalue, int value)
{
Llink new;
New = (llink) malloc (sizeof (node ));
If (! New)
{
Return NULL;
}
New-> num = value;
New-> next = NULL;
// Find the node
Llink getnode;
Getnode = findnode (head, nodevalue );
// If no node is found, it is inserted before the first node.
If (getnode = NULL)
{
New-> next = ptr-> next;
Ptr-> next = new;
}
Else // locate the specified node and insert it after the specified Node
{
New-> next = getnode-> next;
Getnode-> next = new;
}
Return head;
}
Int main (int argc, char * argv [])
{
Int llist1 [6] = {1, 2, 3, 4, 5, 6 };
Llink head;
Head = createllist (llist1, 6 );
If (! Head)
{
Exit (1 );
}
Printf ("original linked list :");
Printllist (head );
Head = insertnode (head, head, 6, 23 );
Printf ("inserted linked list :");
Printllist (head );
}