c++实现链表逆置(数据结构)
时间: 2023-11-12 07:04:05 浏览: 100
用C++实现逆置链表
链表逆置是将链表中的节点顺序颠倒。以下是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* current = head;
Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
// 打印链表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
// 创建链表
Node* head = malloc(sizeof(Node));
Node* second = malloc(sizeof(Node));
Node* third = malloc(sizeof(Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("原链表: ");
printList(head);
// 链表逆置
Node* newHead = reverseList(head);
printf("逆置后的链表: ");
printList(newHead);
// 释放内存
free(head);
free(second);
free(third);
return 0;
}
```
输出结果:
```
原链表: 1 2 3
逆置后的链表: 3 2 1
```
阅读全文