C++ curr->next = prev; prev = curr;
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <iostream> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* ReverseList(ListNode* head) { // write code here ListNode *prev = nullptr; ListNode *curr = head; while (curr != nullptr) { // O(n) ListNode* t = curr->next; curr->next = prev; // 不断让当前的指向之前的 prev = curr; curr = t; } return prev; } };
这个也能过,但是O(n^n)
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <iostream> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* ReverseList(ListNode* head) { // write code here ListNode *p = head; ListNode *qhead = new ListNode(-1); ListNode *q = qhead; if (!p) { return p; } while (p->next) { if (!p->next->next) { q->next = p->next; q = q->next; p->next = nullptr; p = head; // O(n^n) } else { p = p->next; } } q->next = p; return qhead->next; } };