题解 | #反转链表#没有方法,遍历硬搞。
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <algorithm> #include <list> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ //方法:用三个指针遍历,硬搞。时间复杂:O(n),空间复杂:O(1)(好像和参考答案完全不一样hhh) ListNode* ReverseList(ListNode* head) { //空链表 if (head == nullptr) { return nullptr; } ListNode* p = head->next;//第二个指针 //仅一个元素的列表 if(p==nullptr) return head; ListNode* q = p->next;//第三个指针 head->next = nullptr;//防止结尾循环列表 while(true){//这里不可以用q当条件,会导致最后一个节点录取不到 p->next = head; head = p; p = q; if(p==nullptr){ return head; } q = q->next; } return head; } };