温馨提示×

C语言反转列表的方法是什么

小亿
90
2023-10-26 20:14:31
栏目: 编程语言

在C语言中,可以通过指针操作来反转一个链表。

首先,需要定义一个结构体表示链表的节点,结构体中包含存储的值(可以是任何类型)和一个指向下一个节点的指针。

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

然后,可以编写一个函数来反转链表。该函数需要接收链表的头节点作为参数,然后通过指针操作重新排列链表节点的顺序。

struct Node* reverseList(struct Node* head) {
    struct Node* prev = NULL;
    struct Node* current = head;
    struct Node* next = NULL;
    
    while (current != NULL) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    
    head = prev;
    
    return head;
}

这个函数使用了三个指针:prev用于保存当前节点的前一个节点,current用于保存当前节点,next用于保存当前节点的下一个节点。在循环中,首先将next指针指向当前节点的下一个节点,然后将当前节点的next指针指向前一个节点,接着将prev指针指向当前节点,将current指针指向next节点。最后,将头节点指向反转后的链表的最后一个节点。

以下是一个使用反转链表函数的例子:

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

    // 创建链表
    head = (struct Node*)malloc(sizeof(struct Node));
    second = (struct Node*)malloc(sizeof(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;

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

    // 打印反转后的链表
    struct Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }

    return 0;
}

输出结果为:3 2 1,表示链表已成功反转。

0