51.png

    1. /*
    2. 设单链表的表头指针为h,节点结构由data和next两个域构成,其中data域为字符型。
    3. 试设计算法判断该链表的全部n个字符是否是中心对称,例如xyx,xyyx都是中心对称。
    4. 分析:
    5. 我们可以利用栈的先进后出的特性来搞定这道题,我们设置两个快慢指针,fast和slow
    6. 之前我们就用过这种方法,用以找到中间节点,之后将slow节点之后的节点依次入栈,
    7. fast指针重新指向首节点,然后fast和栈内元素一一比较,若存在不同,则不对称。
    8. */
    9. struct Link {
    10. union {
    11. char letter;
    12. }type;
    13. struct Link *next;
    14. };
    15. struct Stack {
    16. char *arr;
    17. int len;
    18. int top;
    19. };
    20. #define _CRT_SECURE_NO_WARNINGS
    21. #include <stdio.h>
    22. void isSymmetry(Link *h) {
    23. int size;
    24. struct Stack *s;
    25. Stack *createStack(int);
    26. bool push(Stack *,char);
    27. bool empty(Stack *);
    28. char *top(Stack *);
    29. bool pop(Stack *);
    30. void destory(Stack *);
    31. printf("请输入要创建的栈的大小:size=");
    32. scanf("%d",&size);
    33. s = createStack(size);
    34. struct Link *fast = h->next, *slow = h->next;
    35. while (fast->next&&fast->next->next) {
    36. fast = fast->next->next;
    37. slow = slow->next;
    38. }
    39. fast = h->next;
    40. while (slow->next) {//将中间元素的后面节点依次入栈
    41. push(s,slow->next->type.letter);
    42. slow = slow->next;//我总是忘记往下走
    43. }
    44. while (!empty(s)) {
    45. if (fast->type.letter != *top(s) ) {
    46. printf("该链表非中心对称");
    47. break;
    48. }
    49. fast = fast->next;
    50. pop(s);
    51. }
    52. if(empty(s))printf("该链表是中心对称的");
    53. destory(s);//最后销毁栈
    54. }
    55. int main() {
    56. struct Link *head;
    57. Link *createLink(int);
    58. head = createLink(1);
    59. isSymmetry(head);
    60. return 0;
    61. }
    62. 一名谦虚的学生