C linked list, C Language
# Include <stdio. h>
# Include <malloc. h>
# Include <stdlib. h>
Typedef struct Node
{
Int data;
Node * pNext;
} NODE, * PNODE;
PNODE create_List ();
Void traverse_List (PNODE pHead );
Bool is_empty (PNODE pHead );
Int length_List (PNODE pHead );
Bool insert_List (PNODE pHead, int position, int num );
Bool delete_List (PNODE pHead, int position, int * num );
Void sort_List (PNODE pHead );
Int main ()
{
Int num;
PNODE pHead = NULL;
PHead = create_List ();
Traverse_List (pHead );
If (is_empty (pHead ))
{
Printf ("Empty linked list \ n ");
}
Printf ("the chain table length is % d \ n", length_List (pHead ));
Sort_List (pHead );
Printf ("sorted: \ n ");
Traverse_List (pHead );
Insert_List (pHead, 2, 2 );
Printf ("after adding an element: \ n ");
Traverse_List (pHead );
Delete_List (pHead, 2, & num );
Printf ("delete element 2 with a value of % d: \ n", num );
Traverse_List (pHead );
Return 0;
}
PNODE create_List ()
{
Int len;
Int val;
PNODE pHead = (PNODE) malloc (sizeof (NODE ));
If (NULL = pHead)
{
Printf ("Allocation failed, Program terminated \ n ");
Exit (0 );
}
PNODE pTail = pHead;
PTail-> pNext = NULL;
Printf ("Enter the number of nodes to be generated :");
Scanf ("% d", & len );
For (int I = 0; I <len; I ++)
{
Printf ("Enter the value of node % d:", I + 1 );
Scanf ("% d", & val );
PNODE pNew = (PNODE) malloc (sizeof (NODE ));
If (NULL = pNew)
{
Printf ("Allocation failed, Program terminated \ n ");
Exit (0 );
}
PNew-> data = val;
PTail-> pNext = pNew;
PNew-> pNext = NULL;
PTail = pNew;
}
Return pHead;
}
Void traverse_List (PNODE pHead)
{
PNODE temp = pHead-> pNext;
While (temp! = NULL)
{
Printf ("% d \ n", temp-> data );
Temp = temp-> pNext;
}
}
Bool is_empty (PNODE pHead)
{
If (NULL = pHead-> pNext)
{
Return true;
}
Else
{
Return false;
}
}
Int length_List (PNODE pHead)
{
Int len = 0;
PNODE temp = pHead-> pNext;
While (temp)
{
Len ++;
Temp = temp-> pNext;
}
Return len;
}
Void sort_List (PNODE pHead)
{
PNODE p, q;
Int I, j, temp;
Int len = length_List (pHead );
For (I = 0, p = pHead-> pNext; I <len-1; I ++, p = p-> pNext)
{
For (j = I + 1, q = p-> pNext; j <len; j ++, q = q-> pNext)
{
If (q-> data <p-> data)
{
Temp = q-> data;
Q-> data = p-> data;
P-> data = temp;
}
}
}
}
Bool insert_List (PNODE pHead, int position, int num)
{
Int I = 0;
PNODE p = pHead;
While (NULL! = P & I <position-1)
{
P = p-> pNext;
I ++;
}
If (I> position-I | NULL = p)
{
Return false;
}
PNODE pNew = (PNODE) malloc (sizeof (NODE ));
If (NULL = pNew)
{
Printf ("Allocation failed, Program terminated \ n ");
Exit (0 );
}
PNew-> data = num;
PNew-> pNext = p-> pNext;
P-> pNext = pNew;
Return true;
}
Bool delete_List (PNODE pHead, int position, int * num)
{
Int I = 0;
PNODE p = pHead;
While (NULL! = P-> pNext & I <position-1)
{
P = p-> pNext;
I ++;
}
If (I> position-I | NULL = p-> pNext)
{
Return false;
}
PNODE q = p-> pNext;
* Num = q-> data;
P-> pNext = p-> pNext;
Free (q );
Q = NULL;
Return true;
}