题解 | 反转链表
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
反转链表大致思路
- 首先找到尾指针
- 通过头指针与向尾指针利用头插法进行插入操作
- 重复上述步骤直至头指针指向尾指针
注意:本题需要判断头指针是否为空
/** * 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 if (head == NULL) { return NULL; } ListNode* rear = head; while(rear->next != NULL) { rear = rear->next; } ListNode* p = head; ListNode* p_next = head->next; while(p != rear) { p->next = rear->next; rear->next = p; p = p_next; p_next = p->next; } return rear; } };