#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) { } }; class Solution { public: ListNode* reverseList(ListNode* head) { if (head == nullptr || head->next == nullptr) { return head; } ListNode* cur = head; ListNode* pre = nullptr; while (cur != nullptr) { ListNode* next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } }; int main() { ListNode* node1 = new ListNode(1); ListNode* node2 = new ListNode(2); ListNode* node3 = new ListNode(3); ListNode* node4 = new ListNode(4); node1->next = node2; node2->next = node3; node3->next = node4; ListNode* head = node1; ListNode* cur = node1; cout << "翻转之前的链表为:"; while (cur != nullptr) { cout << cur->val <<"->"; cur = cur->next; } cout << "nullptr" << endl; Solution solution; cur = solution.reverseList(head); cout << "翻转之后的链表为:"; while (cur != nullptr) { cout << cur->val << "->"; cur = cur->next; } cout << "nullptr" << endl; return 0; }