用c语言写单链表的就地逆置
时间: 2023-10-10 10:06:48 浏览: 100
单链表的逆置(c语言)
好的,下面是用C语言实现单链表就地逆置的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList(int n) {
Node *head = NULL, *tail = NULL;
int i, val;
for (i = 0; i < n; i++) {
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &val);
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = val;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void printList(Node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
void reverseList(Node **head) {
if (*head == NULL || (*head)->next == NULL) {
return;
}
Node *prev = NULL, *curr = *head, *next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
*head = prev;
}
int main() {
int n;
printf("请输入链表的长度:");
scanf("%d", &n);
Node *head = createList(n);
printf("原始链表:");
printList(head);
reverseList(&head);
printf("逆置后的链表:");
printList(head);
return 0;
}
```
该代码首先定义了一个`Node`结构体表示链表中的节点,包含了一个整数`data`和下一个节点的指针`next`。然后通过`createList`函数创建了一个长度为`n`的单链表,通过`printList`函数打印出了原始链表。接着通过`reverseList`函数实现了单链表的就地逆置,最后再次通过`printList`函数打印出了逆置后的链表。
阅读全文