假若s,p,q是連續三個結點的指針,若我們要在p前插入一個新結點r,則只需把s的右鏈域指針指向r,r的左鏈域指針指向s,r的右鏈域指針指向p,p的左鏈域指針指向r即可。
在p,q之間插入原理也一樣。
下面就是一個應用雙向循環鏈表插入算法的例子:
- #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("不能分配內存空間!");
- exit(0);
- }
- h->name[0]='/0';
- h->llink=NULL;
- h->rlink=NULL;
- p=h;
- for(i=0;i<n;i++)
- {
- if((s= (stud *) malloc(sizeof(stud)))==NULL)
- {
- printf("不能分配內存空間!");
- exit(0);
- }
- p->rlink=s;
- printf("請輸入第%d個人的姓名",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("沒有查找到該數據!");
- }
- void print(stud *h)
- {
- int n;
- stud *p;
- p=h->rlink;
- printf("數據信息爲:/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("不能分配內存空間!");
- exit(0);
- }
- printf("請輸入你要插入的人的姓名:");
- 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("請輸入你要查找的人的姓名:");
- scanf("%s",studname);
- searchpoint=search(head,studname);
- printf("你所要查找的人的姓名是:%s/n",*&searchpoint->name);
- insert(searchpoint);
- print(head);
- }