#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode():val(0),next(nullptr){}
ListNode(int _val):val(_val),next(nullptr){}
ListNode(int _val,ListNode* _next):val(_val),next(_next){}
};
ListNode* init() {
ListNode* head = new ListNode(1);
ListNode* node1 = new ListNode(2);
ListNode* node2 = new ListNode(3);
ListNode* node3 = new ListNode(4);
ListNode* node4 = new ListNode(5);
head->next = node1;
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = nullptr;
return head;
}
ListNode* reverse(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while (cur != nullptr) {
ListNode* nt = cur->next;
cur->next = pre;
pre = cur;
cur = nt;
}
return pre;
}
int main() {
auto head = init();
head = reverse(head);
while (head != nullptr) {
cout << head->val << " ";
head = head->next;
}
return 0;
}
VS 上手撕反转链表题(注意链表结构体的定义及链表的初始化)
最新推荐文章于 2024-08-20 15:59:15 发布