单链表的就地逆置的C语言代码
时间: 2024-06-12 09:09:10 浏览: 11
单链表就地逆置是指不申请新的空间,在原链表上修改指针的指向,实现链表的反转。下面是一个用C语言实现单链表就地逆置的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点的结构体
struct Node {
int data;
struct Node* next;
};
// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 就地逆置单链表
struct Node* reverseLinkedList(struct Node* head) {
struct Node *prev = NULL, *next = NULL;
while (head != NULL) {
next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
// 打印链表
void printLinkedList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
// 创建链表
struct Node* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);
printf("原链表:");
printLinkedList(head);
head = reverseLinkedList(head);
printf("逆置后的链表:");
printLinkedList(head);
return 0;
}
```
以上代码会创建一个包含 1、2、3、4 的链表,然后调用 `reverseLinkedList` 函数进行链表的就地逆置,并最终打印出逆置后的链表。