当前位置:   article > 正文

已知p指向双向循环链表中的一个结点,其结点结构为data、prior、next三个域,写出算法change(p),交换p所指向的结点和它的前缀结点的顺序。

已知p指向双向循环链表中的一个结点,其结点结构为data、prior、next三个域,写出算法change(p),交换p所指向的结点和它的前缀结点的顺序。
  1. #include<assert.h>
  2. typedef struct SLnode
  3. {
  4. int data;
  5. struct SLnode* prior;
  6. struct SLnode* next;
  7. }SLnode,*SLnodelist;
  8. //创建结点
  9. SLnode* createhead(int data)
  10. {
  11. SLnode* newnode = (SLnode*)malloc(sizeof(SLnode));
  12. newnode->data = data;
  13. newnode->next = newnode->prior = newnode;
  14. return newnode;
  15. }
  16. //初始化哨兵位
  17. SLnode* ListInit()
  18. {
  19. SLnode* newnode = createhead(0);
  20. }
  21. //尾插
  22. void ListPushBank(SLnode* plist, int x)
  23. {
  24. assert(plist);
  25. SLnode* ret = plist->prior;
  26. SLnode* newnode = createhead(x);
  27. ret->next = newnode;
  28. newnode->next = plist;
  29. newnode->prior = ret;
  30. plist->prior = newnode;
  31. }
  32. void printlist(SLnode* plist)
  33. {
  34. SLnode* ret = plist->next;
  35. while (ret != plist)
  36. {
  37. printf("%d->", ret->data);
  38. ret = ret->next;
  39. }
  40. printf("NULL\n");
  41. }
  42. void change(SLnodelist p)
  43. {
  44. SLnodelist q;
  45. q = p->prior;
  46. q->prior->next = p;
  47. p->prior = q->prior;
  48. q->next = p->next;
  49. p->next->prior = q;
  50. q->prior = p;
  51. p->next = q;
  52. }
  53. int main()
  54. {
  55. int n, num;
  56. SLnode* plist = ListInit();
  57. printf("请输入链表的长度\n");
  58. scanf("%d", &n);
  59. printf("请输入元素\n");
  60. for (int i = 0; i < n; i++)
  61. {
  62. scanf("%d", &num);
  63. ListPushBank(plist,num);
  64. }
  65. printf("双链表的元素如下\n");
  66. printlist(plist);
  67. printf("请输入你要交换的的结点的值\n");
  68. SLnodelist q = (SLnodelist)malloc(sizeof(SLnode));
  69. scanf("%d", &q->data);
  70. SLnodelist p;
  71. p = plist->next;
  72. while (p != plist)
  73. {
  74. if (p->data == q->data)
  75. {
  76. change(p);
  77. break;
  78. }
  79. else
  80. {
  81. p = p->next;
  82. }
  83. }
  84. printf("交换后\n");
  85. printlist(plist);
  86. return 0;
  87. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/990041
推荐阅读
相关标签
  

闽ICP备14008679号