23.png

    1. /*
    2. 有一带头结点的链表,设计一算法从尾到头的输出每个节点的值。
    3. 分析:
    4. 这种类型就有点像是栈的性质,我们可以利用递归来处理,出口便是尾元素
    5. */
    6. struct Link {
    7. int data;
    8. struct Link* next;
    9. };
    10. #define _CRT_SECURE_NO_WARNINGS
    11. #include <stdio.h>
    12. #include <stdlib.h>
    13. void reverseOutput(Link *p) {
    14. if (p == NULL) return;
    15. else {
    16. reverseOutput(p->next);
    17. printf("%d ",p->data);
    18. }
    19. }
    20. int main() {
    21. int n,data;
    22. printf("请输入创建链表的节点个数:");
    23. scanf("%d",&n);
    24. struct Link *q;
    25. struct Link *head =(struct Link*) malloc(sizeof(struct Link));
    26. head->next = NULL;
    27. q = head;
    28. for (int i = 0; i < n;i++) {
    29. struct Link *newP = (struct Link*) malloc(sizeof(struct Link));
    30. printf("请输入第一个节点的值:");
    31. scanf("%d",&data);
    32. newP->data = data;
    33. newP->next = NULL;
    34. head->next = newP;
    35. head = head->next;//head要始终指向最新节点
    36. }
    37. head->next = NULL;
    38. head = q;//最后head要指向头结点
    39. reverseOutput(head->next);
    40. return 0;
    41. }