可以通过迭代的方式实现单向链表的反转。具体步骤如下:

  1. 定义一个指针变量prev,用于保存当前节点的前一个节点,初始值为NULL
  2. 定义一个指针变量current,用于保存当前节点,初始值为链表的头节点。
  3. 定义一个指针变量next,用于保存当前节点的下一个节点。
  4. 循环遍历链表,直到当前节点为NULL,每次迭代执行以下操作:
    1. next指向当前节点的下一个节点。
    2. 将当前节点的next指针指向prev
    3. 更新prev为当前节点。
    4. 更新currentnext
  5. 最后将链表的头节点指向prev,完成反转。

以下为具体实现代码:

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

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

// 创建链表节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 反转链表
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;
}

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

int main() {
    // 创建链表:1->2->3->4->5
    Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = createNode(5);

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

    // 反转链表
    head = reverseList(head);

    printf("反转后的链表:");
    printList(head);

    return 0;
}

运行结果为:

原链表:1 2 3 4 5 
反转后的链表:5 4 3 2 1 
``
C语言编程实现单向链表反转:1-2-3-4-5反转后:5-4-3-2-1

原文地址: https://www.cveoy.top/t/topic/iTvw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录