用C++代码写一个链表倒转
时间: 2023-12-27 12:45:29 浏览: 82
以下是使用C语言实现链表倒转的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* head)
{
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
}
void reverseList(struct Node** head)
{
struct Node* prev = NULL;
struct Node* current = *head;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("Original List: ");
printList(head);
reverseList(&head);
printf("\nReversed List: ");
printList(head);
return 0;
}
```
输出结果:
```
Original List: 1 2 3
Reversed List: 3 2 1
```
该代码创建了一个包含3个节点的链表,并使用`printList()`函数打印原始列表和反转后的列表。`reverseList()`函数使用三个指针变量来反转链表中的节点。最后,`main()`函数调用`reverseList()`函数来反转链表并打印结果。
阅读全文