C语言单向链表反转算法详解及代码示例

本文将详细介绍使用C语言建立单向链表并实现节点逆转的算法,并提供完整的代码示例。通过清晰的步骤和注释,帮助读者理解链表结构和反转操作的原理。

1. 链表结构定义

首先,我们需要定义一个链表节点的结构体,它包含一个整数数据和一个指向下一个节点的指针。

#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构
typedef struct Node {
    int data;
    struct Node* next;
} Node;

2. 链表操作函数

接下来,我们需要实现一些基本的链表操作函数,包括创建节点、在链表末尾添加节点、反转链表、打印链表和释放链表内存等。

2.1 创建节点

// 创建链表节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (newNode == NULL) {
        printf("内存分配失败!\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

2.2 在链表末尾添加节点

// 在链表末尾添加节点
Node* appendNode(Node* head, int data) {
    Node* newNode = createNode(data);
    if (head == NULL) {
        return newNode;
    }
    Node* current = head;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = newNode;
    return head;
}

2.3 反转链表

// 反转链表
Node* reverseList(Node* head) {
    Node* prev = NULL;
    Node* current = head;
    Node* next = NULL;
    while (current != NULL) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    return prev;
}

2.4 打印链表

// 打印链表
void printList(Node* head) {
    Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

2.5 释放链表内存

// 释放链表内存
void freeList(Node* head) {
    Node* current = head;
    Node* next = NULL;
    while (current != NULL) {
        next = current->next;
        free(current);
        current = next;
    }
}

3. 主函数示例

int main() {
    Node* head = NULL;
    head = appendNode(head, 1);
    head = appendNode(head, 2);
    head = appendNode(head, 3);
    head = appendNode(head, 4);
    head = appendNode(head, 5);

    printf("原始链表:");
    printList(head);

    head = reverseList(head);

    printf("逆转链表:");
    printList(head);

    freeList(head);
    return 0;
}

4. 运行结果

原始链表:1 2 3 4 5 
逆转链表:5 4 3 2 1 

总结

本文详细介绍了使用C语言建立单向链表并实现节点逆转的算法,并提供了完整的代码示例。希望对读者学习和理解链表结构和反转操作有所帮助。

C语言单向链表反转算法详解及代码示例