c语言怎么逆置链表

逆置链表是指将一个链表中的元素顺序颠倒过来,下面是一个详细的步骤,使用C语言实现逆置链表:

c语言怎么逆置链表
(图片来源网络,侵删)

1、定义链表节点结构体:

struct ListNode {
    int val; // 节点的值
    struct ListNode *next; // 指向下一个节点的指针
};

2、创建一个新的空链表头节点:

struct ListNode* reverseList(struct ListNode* head) {
    // 创建一个新的空链表头节点
    struct ListNode* newHead = NULL;
    // ...
}

3、遍历原链表,将每个节点插入到新链表的头部:

struct ListNode* reverseList(struct ListNode* head) {
    // 创建一个新的空链表头节点
    struct ListNode* newHead = NULL;
    // 遍历原链表,将每个节点插入到新链表的头部
    while (head != NULL) {
        // 保存当前节点的下一个节点指针
        struct ListNode* next = head>next;
        // 将当前节点插入到新链表的头部
        head>next = newHead;
        // 更新新链表头节点为当前节点
        newHead = head;
        // 移动到下一个节点
        head = next;
    }
    // 返回新链表的头节点
    return newHead;
}

4、完整代码示例:

#include <stdio.h>
#include <stdlib.h>
struct ListNode {
    int val; // 节点的值
    struct ListNode *next; // 指向下一个节点的指针
};
// 创建新的节点并初始化值和指针域为NULL
struct ListNode* createNode(int val) {
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newNode>val = val;
    newNode>next = NULL;
    return newNode;
}
// 逆置链表函数实现
struct ListNode* reverseList(struct ListNode* head) {
    // 创建一个新的空链表头节点
    struct ListNode* newHead = NULL;
    // 遍历原链表,将每个节点插入到新链表的头部
    while (head != NULL) {
        // 保存当前节点的下一个节点指针
        struct ListNode* next = head>next;
        // 将当前节点插入到新链表的头部
        head>next = newHead;
        // 更新新链表头节点为当前节点
        newHead = head;
        // 移动到下一个节点
        head = next;
    }
    // 返回新链表的头节点
    return newHead;
}
// 打印链表函数实现(用于测试)
void printList(struct ListNode* head) {
    struct ListNode* current = head;
    while (current != NULL) {
        printf("%d ", current>val); // 打印当前节点的值
        current = current>next; // 移动到下一个节点
    }
    printf("
"); // 换行符,使输出更清晰可读
}
int main() {
    // 创建一个包含5个节点的链表:1 > 2 > 3 > 4 > 5 > NULL
    struct ListNode* head = createNode(1); // 创建头节点并赋值为1,指针域为NULL(初始时)
    head>next = createNode(2); // 创建第二个节点并赋值为2,指针域指向头节点(初始时)
    head>next>next = createNode(3); // 创建第三个节点并赋值为3,指针域指向第二个节点(初始时)

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/414028.html

(0)
未希新媒体运营
上一篇 2024-03-31 11:04
下一篇 2024-03-31 11:06

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入