【快慢指针】LeetCode 143. 重排链表
1.【快慢指针】LeetCode 143. 重排链表
题解
用快慢指针先找到中间结点,然后断开前后两条链,用头插法的思路逆转后面那条链,最后两条链依次从前往后遍历插入即可。
参考代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: void reorderList(ListNode* head) { if (head -> next == nullptr) return ; ListNode* slow = head, *fast = head -> next; while (fast != nullptr && fast -> next != nullptr) { slow = slow -> next; fast = fast -> next -> next; } fast = slow -> next; slow -> next = nullptr; slow = head; ListNode* h = new ListNode(); while (fast != nullptr) { ListNode* node = fast; fast = fast -> next; node -> next = h -> next; h -> next = node; } while (h -> next != nullptr) { ListNode* node = h -> next; h -> next = h-> next -> next; node -> next = slow -> next; slow -> next = node; slow = node -> next; } } };
分类:
数据结构与算法
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 从 Windows Forms 到微服务的经验教训
· 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee