编写一个代码,使单链表逆置
时间: 2024-05-01 19:16:12 浏览: 71
单链表的逆置 代码
好的,以下是单链表逆置的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node, *PtrToNode;
PtrToNode ReverseList(PtrToNode head) {
PtrToNode prev = NULL;
PtrToNode curr = head;
while (curr) {
PtrToNode next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
PtrToNode head = NULL;
int n;
// Input the linked list
printf("Enter the number of elements: ");
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
int data;
printf("Enter element %d: ", i + 1);
scanf("%d", &data);
PtrToNode node = (PtrToNode)malloc(sizeof(Node));
node->data = data;
node->next = head;
head = node;
}
// Reverse the linked list
head = ReverseList(head);
// Print the linked list
while (head) {
printf("%d ", head->data);
head = head->next;
}
return 0;
}
```
以上代码实现了单链表的逆置,通过不断交换节点的指针实现。
阅读全文