首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C中使用逆

序打印链表?

在C语言中,可以使用递归或迭代的方式来实现逆序打印链表。

递归方法:

递归方法是通过递归调用函数本身来实现的。具体步骤如下:

  1. 判断链表是否为空,若为空则直接返回。
  2. 递归调用函数打印链表的下一个节点。
  3. 打印当前节点的值。

以下是一个使用递归方法打印链表的示例代码:

代码语言:c
复制
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
} Node;

void printListReverse(Node* head) {
    if (head == NULL) {
        return;
    }
    printListReverse(head->next);
    printf("%d ", head->data);
}

int main() {
    Node* head = NULL;
    Node* second = NULL;
    Node* third = NULL;

    head = (Node*)malloc(sizeof(Node));
    second = (Node*)malloc(sizeof(Node));
    third = (Node*)malloc(sizeof(Node));

    head->data = 1;
    head->next = second;

    second->data = 2;
    second->next = third;

    third->data = 3;
    third->next = NULL;

    printf("Original list: ");
    Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    printf("\nReversed list: ");
    printListReverse(head);

    return 0;
}

输出结果为:

代码语言:txt
复制
Original list: 1 2 3
Reversed list: 3 2 1

迭代方法:

迭代方法是通过使用一个辅助栈来实现的。具体步骤如下:

  1. 创建一个空栈。
  2. 遍历链表,将链表的每个节点依次入栈。
  3. 依次出栈并打印栈中的元素。

以下是一个使用迭代方法打印链表的示例代码:

代码语言:c
复制
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
} Node;

void printListReverse(Node* head) {
    Node* stack = NULL;
    Node* current = head;

    while (current != NULL) {
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->data = current->data;
        newNode->next = stack;
        stack = newNode;
        current = current->next;
    }

    printf("Reversed list: ");
    while (stack != NULL) {
        printf("%d ", stack->data);
        Node* temp = stack;
        stack = stack->next;
        free(temp);
    }
}

int main() {
    Node* head = NULL;
    Node* second = NULL;
    Node* third = NULL;

    head = (Node*)malloc(sizeof(Node));
    second = (Node*)malloc(sizeof(Node));
    third = (Node*)malloc(sizeof(Node));

    head->data = 1;
    head->next = second;

    second->data = 2;
    second->next = third;

    third->data = 3;
    third->next = NULL;

    printf("Original list: ");
    Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    printListReverse(head);

    return 0;
}

输出结果为:

代码语言:txt
复制
Original list: 1 2 3
Reversed list: 3 2 1

推荐的腾讯云相关产品和产品介绍链接地址:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

34秒

PS使用教程:如何在Photoshop中合并可见图层?

3分54秒

PS使用教程:如何在Mac版Photoshop中制作烟花效果?

36秒

PS使用教程:如何在Mac版Photoshop中画出对称的图案?

1分6秒

PS使用教程:如何在Mac版Photoshop中制作“3D”立体文字?

11分33秒

061.go数组的使用场景

4分36秒

04、mysql系列之查询窗口的使用

1分55秒

uos下升级hhdesk

1分26秒

PS小白教程:如何在Photoshop中完美合并两张图片?

2分7秒

基于深度强化学习的机械臂位置感知抓取任务

40秒

BOSHIDA 三河博电科技 ACDC专业电源模块 注意事项说明

4分50秒

2.3 电商商城数据结构设计与分析

3分22秒

2.4 设计自然语言对话AI查询的操作流程

领券