设计算法实现将单链表中数据逆置的操作。用C语言代码
时间: 2024-04-29 22:27:13 浏览: 105
好的,我可以为您提供一个C语言的单链表逆置的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node* reverseList(Node *head) {
Node *prev = NULL;
Node *curr = head;
Node *next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
// create linked list 1-2-3-4-5
Node *head = (Node*)malloc(sizeof(Node));
head->data = 1;
Node *node2 = (Node*)malloc(sizeof(Node));
node2->data = 2;
head->next = node2;
Node *node3 = (Node*)malloc(sizeof(Node));
node3->data = 3;
node2->next = node3;
Node *node4 = (Node*)malloc(sizeof(Node));
node4->data = 4;
node3->next = node4;
Node *node5 = (Node*)malloc(sizeof(Node));
node5->data = 5;
node4->next = node5;
node5->next = NULL;
// reverse the linked list
head = reverseList(head);
// print the reversed linked list
Node *temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
// free the memory used by the linked list
temp = head;
while (temp != NULL) {
Node *temp2 = temp->next;
free(temp);
temp = temp2;
}
return 0;
}
```
这个代码使用了迭代法实现单链表的逆置。具体来说,在逆置过程中,我们使用三个指针,分别为`prev`、`curr`和`next`,初始值分别为`NULL`、头结点和头结点的下一个节点。通过循环遍历单链表,依次将当前节点的下一个节点指向前一个节点,然后将三个指针后移一位。最终,逆置完成后,我们将头结点指向新的逆置后的链表的头结点(也就是原先链表的尾节点),并返回该头结点。
阅读全文