雙向循環鏈表的插入

對於雙向循環鏈表,我們現在可以隨意地在某已知結點p前或者p後插入一個新的結點。
假若s,p,q是連續三個結點的指針,若我們要在p前插入一個新結點r,則只需把s的右鏈域指針指向r,r的左鏈域指針指向s,r的右鏈域指針指向p,p的左鏈域指針指向r即可。
在p,q之間插入原理也一樣。
下面就是一個應用雙向循環鏈表插入算法的例子:
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <string.h>
  4. #define N 10
  5. typedef struct node
  6. {
  7. char name[20];
  8. struct node *llink,*rlink;
  9. }stud;
  10. stud * creat(int n)
  11. {
  12. stud *p,*h,*s;
  13. int i;
  14. if((h=(stud *)malloc(sizeof(stud)))==NULL)
  15. {
  16. printf("不能分配內存空間!");
  17. exit(0);
  18. }
  19. h->name[0]='/0';
  20. h->llink=NULL;
  21. h->rlink=NULL;
  22. p=h;
  23. for(i=0;i<n;i++)
  24. {
  25. if((s= (stud *) malloc(sizeof(stud)))==NULL)
  26. {
  27. printf("不能分配內存空間!");
  28. exit(0);
  29. }
  30. p->rlink=s;
  31. printf("請輸入第%d個人的姓名",i+1);
  32. scanf("%s",s->name);
  33. s->llink=p;
  34. s->rlink=NULL;
  35. p=s;
  36. }
  37. h->llink=s;
  38. p->rlink=h;
  39. return(h);
  40. }
  41. stud * search(stud *h,char *x)
  42. {
  43. stud *p;
  44. char *y;
  45. p=h->rlink;
  46. while(p!=h)
  47. {
  48. y=p->name;
  49. if(strcmp(y,x)==0)
  50. return(p);
  51. else p=p->rlink;
  52. }
  53. printf("沒有查找到該數據!");
  54. }
  55. void print(stud *h)
  56. {
  57. int n;
  58. stud *p;
  59. p=h->rlink;
  60. printf("數據信息爲:/n");
  61. while(p!=h)
  62. {
  63. printf("%s ",&*(p->name));
  64. p=p->rlink;
  65. }
  66. printf("/n");
  67. }
  68. void insert(stud *p)
  69. {
  70. char stuname[20];
  71. stud *s;
  72. if((s= (stud *) malloc(sizeof(stud)))==NULL)
  73. {
  74. printf("不能分配內存空間!");
  75. exit(0);
  76. }
  77. printf("請輸入你要插入的人的姓名:");
  78. scanf("%s",stuname);
  79. strcpy(s->name,stuname);
  80. s->rlink=p->rlink;
  81. p->rlink=s;
  82. s->llink=p;
  83. (s->rlink)->llink=s;
  84. }
  85. main()
  86. {
  87. int number;
  88. char studname[20];
  89. stud *head,*searchpoint;
  90. number=N;
  91. clrscr();
  92. head=creat(number);
  93. print(head);
  94. printf("請輸入你要查找的人的姓名:");
  95. scanf("%s",studname);
  96. searchpoint=search(head,studname);
  97. printf("你所要查找的人的姓名是:%s/n",*&searchpoint->name);
  98. insert(searchpoint);
  99. print(head);
  100. }

發佈了26 篇原創文章 · 獲贊 4 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章