Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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;
}
};

最新文章

  1. C标准头文件<ctype.h>
  2. 每天学习一点点--word-break和word-wrap用法和区别
  3. [Codevs 1421]秋静叶&秋穣子(最大-最小博弈)
  4. ecshop /category.php SQL Injection Vul
  5. jQuery—DOM操作
  6. [Asp.Net]状态管理(Session、Application、Cache)
  7. object-c [self class] 和 [self _cmd]
  8. 使用Spring容器
  9. HDU 5451 广义斐波那契数列
  10. WP8_定位新页面中listbox的某项
  11. 网页绘制图表 Google Charts with JavaScript #2 ....与ASP.NET网页结合 (ClientScriptManager.RegisterStartupScript 方法)
  12. 293. Flip Game
  13. Ectouch修改虚拟销售数量的方法
  14. js学习心得(一)(菜鸟)
  15. ASP.NET MVC上传文件----uploadify的使用
  16. 9. VIM 系列 - YouCompleteMe 实现代码补全
  17. 1、roboguide新建工程文件
  18. AUC计算 - 进阶操作
  19. [置顶]ABP框架系列总目录(持续更新)
  20. 五、MYSQL的索引

热门文章

  1. IntelliJ IDEA 安装
  2. 出现命令提示apt-get -f install的解决方法
  3. MP3 Lame 转换 参数 设置(转)
  4. [GO]匿名字段
  5. [GO]结构体指针变量初始化
  6. Html::a 生成 method=post
  7. 【转载】Zookeeper 安装和配置
  8. Linux内核版本
  9. Reconstruction(三维重建)文件被修改
  10. 编写高质量代码改善C#程序的157个建议——建议98:用params减少重复参数