在Linux环境下,可以使用C语言来操作链表。以下是将一个单链表逆序的步骤和相关代码示例:
链表是一种常见的数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。逆序操作就是将链表中的节点顺序颠倒过来。
以下是一个单链表逆序的C语言代码示例:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 函数声明
void reverseList(struct Node** head);
void push(struct Node** head, int new_data);
void printList(struct Node* head);
int main() {
struct Node* head = NULL;
// 创建链表 1->2->3->4->5
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf("Original list:\n");
printList(head);
// 逆序链表
reverseList(&head);
printf("\nReversed list:\n");
printList(head);
return 0;
}
// 逆序链表的函数
void 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; // 移动prev和current指针
current = next;
}
*head = prev; // 更新头指针
}
// 在链表头部插入新节点
void push(struct Node** head, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head);
(*head) = new_node;
}
// 打印链表
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
运行上述代码,可以看到原始链表 1->2->3->4->5
被成功逆序为 5->4->3->2->1
。
通过这种方式,可以有效地对链表进行逆序操作,适用于各种需要调整数据顺序的场景。
领取专属 10元无门槛券
手把手带您无忧上云