手写一个链表的反转
时间: 2023-07-10 19:21:16 浏览: 106
链表的倒置
好的,这里是一个简单的链表反转的示例代码:
```c++
#include <iostream>
using namespace std;
// 链表节点定义
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// 反转链表
ListNode* reverseList(ListNode* head) {
ListNode *prev = NULL;
ListNode *curr = head;
while (curr) {
ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 打印链表
void printList(ListNode *head) {
while (head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main() {
// 创建链表 1 -> 2 -> 3 -> 4 -> 5
ListNode *head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
// 打印原链表
cout << "Original List: ";
printList(head);
// 反转链表
head = reverseList(head);
// 打印反转后的链表
cout << "Reversed List: ";
printList(head);
return 0;
}
```
输出结果为:
```
Original List: 1 2 3 4 5
Reversed List: 5 4 3 2 1
```
阅读全文