36.png

    1. // createDouLoopLink.cpp
    2. #define _CRT_SECURE_NO_WARNINGS
    3. #include <stdlib.h>
    4. #include <stdio.h>
    5. struct Link {
    6. int data;
    7. struct Link *next;
    8. struct Link *pre;
    9. };
    10. Link *createDouLoopLink() {
    11. int n, data;
    12. struct Link *head = (struct Link *)malloc(sizeof(struct Link));
    13. head->next = NULL;
    14. head->pre = NULL;
    15. struct Link *p = head;
    16. printf("请输入节点个数:n=");
    17. scanf("%d", &n);
    18. for (int i = 0; i < n; i++) {
    19. printf("请输入第%d个节点值:", i + 1);
    20. scanf("%d", &data);
    21. struct Link *newP = (struct Link*)malloc(sizeof(struct Link));
    22. newP->data = data;
    23. newP->pre = p;
    24. p->next = newP;
    25. p = newP;
    26. }
    27. p->next = head;
    28. head->pre = p;
    29. return head;
    30. }
    1. /*
    2. 设计一个算法判断带头结点的循环双链表是否对称
    3. 分析:
    4. 简单分析,我们可以设置两个指针,pre和next,从头结点出发,进行比较,若pre与next所指值不同,则不对称,若pre和next指向了同一个节点
    5. 则该循环双链表对称
    6. */
    7. struct Link {
    8. int data;
    9. struct Link *next;
    10. struct Link *pre;
    11. };
    12. #define _CRT_SECURE_NO_WARNINGS
    13. #include <stdlib.h>
    14. #include <stdio.h>
    15. void isSymmetry(Link *h) {
    16. struct Link *pre = h->pre,*next=h->next;
    17. while (pre!=next&&pre->pre!=next) {//此时存在两种情况,奇数个节点和偶数个节点都要考虑
    18. if (pre->data!=next->data) {
    19. printf("该循环双链表不对称");
    20. break;
    21. }
    22. else {
    23. pre = pre->pre;
    24. next = next->next;
    25. }
    26. }
    27. if (pre==next||pre->pre==next) {
    28. printf("该循环双链表对称");
    29. }
    30. }
    31. int main() {
    32. struct Link *head;
    33. Link *createDouLoopLink();
    34. head = createDouLoopLink();
    35. isSymmetry(head);
    36. return 0;
    37. }