【Leetcode】Reorder List
2024-08-31 03:29:47
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
快慢指针找到链表中点,将链表分为两段,翻转后半段,再合并两个子链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode *head) {
if (head == nullptr || head->next == nullptr || head->next->next == nullptr) {
return;
}
ListNode *fast = head, *slow = head;
while (fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
slow->next = nullptr;
fast = reverseList(fast);
head = mergeList(head, fast);
}
private:
ListNode * reverseList(ListNode *head) {
ListNode dummy(-);
ListNode *p = &dummy;
while (head) {
ListNode *temp = head->next;
head->next = p->next;
p->next = head;
head = temp;
}
return dummy.next;
} ListNode *mergeList(ListNode *l1, ListNode *l2) {
ListNode dummy(-);
ListNode *p = &dummy;
while (l1) {
p->next = l1;
l1 = l1->next;
p = p->next;
if (l2) {
p->next = l2;
l2 = l2->next;
p = p->next;
}
}
return dummy.next;
}
};
最新文章
- C标准头文件<;ctype.h>;
- 每天学习一点点--word-break和word-wrap用法和区别
- [Codevs 1421]秋静叶&;秋穣子(最大-最小博弈)
- ecshop /category.php SQL Injection Vul
- jQuery—DOM操作
- [Asp.Net]状态管理(Session、Application、Cache)
- object-c [self class] 和 [self _cmd]
- 使用Spring容器
- HDU 5451 广义斐波那契数列
- WP8_定位新页面中listbox的某项
- 网页绘制图表 Google Charts with JavaScript #2 ....与ASP.NET网页结合 (ClientScriptManager.RegisterStartupScript 方法)
- 293.	Flip Game
- Ectouch修改虚拟销售数量的方法
- js学习心得(一)(菜鸟)
- ASP.NET MVC上传文件----uploadify的使用
- 9. VIM 系列 - YouCompleteMe 实现代码补全
- 1、roboguide新建工程文件
- AUC计算 - 进阶操作
- [置顶]ABP框架系列总目录(持续更新)
- 五、MYSQL的索引