2. Insert
For bidirectional cyclic lists, we can now randomly insert a new node at a known node P or p.
If S,p,q is a pointer to three consecutive nodes, if we want to insert a new node R before P, simply point the right link field pointer of S to R,r's left chain field pointer to the S,R right chain field pointer to the P,P left chain field pointer to R.
The insertion principle between p,q is also the same.
Here is an example of applying a bidirectional cyclic link-list insertion algorithm:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define N 10
typedef struct NODE
{
Char name[20];
struct node *llink,*rlink;
}stud;
Stud * creat (int n)
{
Stud *p,*h,*s;
int i;
if ((h= (Stud *) malloc (sizeof (stud))) ==null)
{
printf ("Cannot allocate memory space!");
Exit (0);
}
H->name[0]= ' ";
h->llink=null;
h->rlink=null;
P=h;
for (i=0;i<n;i++)
{
if ((s= (Stud *) malloc (sizeof (stud))) ==null)
{
printf ("Cannot allocate memory space!");
Exit (0);
}
p->rlink=s;
printf ("Please enter the name of%d person", i+1);
scanf ("%s", s->name);
s->llink=p;
s->rlink=null;
P=s;
}
h->llink=s;
p->rlink=h;
return (h);
}
Stud * Search (stud *h,char *x)
{
Stud *p;
Char *y;
p=h->rlink;
while (P!=H)
{
y=p->name;
if (strcmp (y,x) ==0)
return (p);
else p=p->rlink;
}
printf ("No find this data!");
}
void print (Stud *h)
{
int n;
Stud *p;
p=h->rlink;
printf ("Data information is: \ n");
while (P!=H)
{
printf ("%s", &* (P->name));
p=p->rlink;
}
printf ("\ n");
}
void Insert (stud *p)
{
Char stuname[20];
Stud *s;
if ((s= (Stud *) malloc (sizeof (stud))) ==null)
{
printf ("Cannot allocate memory space!");
Exit (0);
}
printf ("Please enter the name of the person you want to insert:");
scanf ("%s", stuname);
strcpy (S->name,stuname);
s->rlink=p->rlink;
p->rlink=s;
s->llink=p;
(S->rlink)->llink=s;
}
Main ()
{
int number;
Char studname[20];
Stud *head,*searchpoint;
Number=n;
CLRSCR ();
Head=creat (number);
Print (head);
printf ("Please enter the name of the person you are looking for:");
scanf ("%s", studname);
Searchpoint=search (Head,studname);
printf ("The name of the person you are looking for is:%s\n", *&searchpoint->name);
Insert (Searchpoint);
Print (head);
}