题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* ReverseList(ListNode* head) { // write code here #if 0 //迭代反转 if(head == nullptr || head->next == nullptr) return head; ListNode* beg = nullptr; ListNode* mid = head; ListNode* end = head->next; while (1) { //修改mid所指节点指向beg mid->next = beg; //判断end if(end == nullptr) break; //调整向后移动 beg = mid; mid = end; end = end->next; } //修改head头指针的指向 head = mid; return head; #else //接地逆置 if(head == nullptr || head->next == nullptr) return head; ListNode* prev = nullptr; ListNode* curr = head; while (curr) { ListNode* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; #endif } };