用c编写单链表的逆置代码
时间: 2024-12-02 21:19:45 浏览: 23
在C语言中,单链表的逆置可以使用迭代的方式实现。下面是一个基本的代码示例:
```c
#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));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表尾部
void appendNode(Node** head, int data) {
if (*head == NULL) {
*head = createNode(data);
} else {
Node* last = *head;
while (last->next != NULL) {
last = last->next;
}
last->next = createNode(data);
}
}
// 逆置链表
Node* reverseList(Node* head) {
Node* prev = NULL;
Node* current = head;
Node* nextTemp = NULL;
while (current != NULL) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
// 打印链表
void printList(Node* node) {
while (node != NULL) {
printf("%d ->", node->data);
node = node->next;
}
printf("NULL\n");
}
int main() {
Node* head = NULL;
// 添加一些节点到链表
appendNode(&head, 1);
appendNode(&head, 2);
appendNode(&head, 3);
appendNode(&head, 4);
appendNode(&head, 5);
printf("Original List:\n");
printList(head);
head = reverseList(head);
printf("\nReversed List:\n");
printList(head);
return 0;
}
```
在这个例子中,我们首先创建了一个链表并添加了一些节点。然后通过`reverseList`函数逆置了链表,并最后打印出逆置后的链表。
阅读全文