请用c语言写程序,将一个单向链表反向连接;
时间: 2024-05-11 15:14:35 浏览: 117
以下是一个反转单向链表的示例C程序:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
struct Node {
int data;
struct Node* next;
};
// 创建链表
struct Node* createList(int arr[], int n) {
struct Node* head = NULL;
struct Node* tail = NULL;
for (int i = 0; i < n; i++) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = arr[i];
node->next = NULL;
if (head == NULL) {
head = node;
} else {
tail->next = node;
}
tail = node;
}
return head;
}
// 反转链表
struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL;
struct Node* curr = head;
while (curr != NULL) {
struct Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 打印链表
void printList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(int);
struct Node* head = createList(arr, n);
printf("Original List: ");
printList(head);
head = reverseList(head);
printf("Reversed List: ");
printList(head);
return 0;
}
```
该程序首先创建一个单向链表,然后调用 `reverseList()` 函数来反转它。 `reverseList()` 函数使用三个指针来反转链表:`prev` 用于保持反转后的链表头, `curr` 用于迭代原链表, `next` 用于暂存 `curr->next`,以便在修改 `curr->next` 之前访问下一个节点。最后,该程序打印原始链表和反转链表。
阅读全文