How to reverse a singly-linked list in C language?

To reverse a singly linked list, you can use three pointers pointing to the current node, the previous node, and the next node. Then, reverse the linked list by changing the direction of the pointers.

The specific steps are as follows:

  1. Initialize three pointers: the pointer cur points to the head node of the linked list, the pointer prev points to NULL, and the pointer next points to NULL.
  2. Traverse the linked list until the current node pointer ‘cur’ is NULL.
  3. During the traversal process, the pointer next of the following node is first directed towards the next node of the current node cur.
  4. Then set the next node pointer of the current node cur to the previous node prev.
  5. Then set the previous node pointer prev to point to the current node pointer cur.
  6. Finally, the current node pointer “cur” is assigned to the next node pointer.
  7. Repeat steps 2-6 until the entire linked list is traversed.
  8. Finally, by pointing the head node pointer of the linked list to the pointer of the previous node prev, the reversal of the linked list can be completed.

Here is an example code implementation:

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

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

// 反转链表函数
struct Node* reverseLinkedList(struct Node* head) {
    struct Node* cur = head;
    struct Node* prev = NULL;
    struct Node* next = NULL;

    while (cur != NULL) {
        next = cur->next; // 暂存当前节点的下一个节点
        cur->next = prev; // 将当前节点的下一个节点指向前一个节点,实现翻转
        prev = cur; // 前一个节点指针后移
        cur = next; // 当前节点指针后移
    }

    head = prev; // 将链表头节点指向翻转后的链表的头节点

    return head;
}

// 打印链表函数
void printLinkedList(struct Node* head) {
    struct Node* cur = head;

    while (cur != NULL) {
        printf("%d ", cur->data);
        cur = cur->next;
    }

    printf("\n");
}

int main() {
    // 创建链表
    struct Node* head = (struct Node*)malloc(sizeof(struct Node));
    struct Node* second = (struct Node*)malloc(sizeof(struct Node));
    struct Node* third = (struct Node*)malloc(sizeof(struct Node));

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

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

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

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

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

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

    // 释放内存
    free(head);
    free(second);
    free(third);

    return 0;
}

The code above creates a linked list with 3 nodes, then calls the reverseLinkedList function to reverse the list, and uses the printLinkedList function to print the result. Finally, memory allocated dynamically is released.

The results are as follows:

原始链表:1 2 3 
反转后的链表:3 2 1 
bannerAds