#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 ("The list is empty \ n");
}
printf ("Linked list length is%d\n", Length_list (Phead));
Sort_list (Phead);
printf ("After sorting: \ n");
Traverse_list (Phead);
Insert_list (phead,2,2);
printf ("After adding elements: \ n");
Traverse_list (Phead);
Delete_list (Phead,2,&num);
printf ("Delete element 2 with value%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 ("Please enter the number of nodes to generate:");
scanf ("%d", &len);
for (int i=0;i<len;i++)
{
printf ("Please enter the value of%d nodes:", 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->pnext;
Free (q);
Q=null;
return true;
}
C-language linked list