Reorder List 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/reorder-list/description/


Description

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}.

Solution

typedef struct ListNode ListNode;

// reverse linked list with head node
void reverseList(struct ListNode* head) {
if (head == NULL || head -> next == NULL || head -> next -> next == NULL)
return; ListNode *preNode = head -> next;
ListNode *tail = preNode;
ListNode *curNode = preNode -> next;
ListNode *nextNode;
while (curNode != NULL) {
nextNode = curNode -> next;
curNode -> next = preNode;
preNode = curNode;
curNode = nextNode;
} head -> next = preNode;
tail -> next = NULL;
} void reorderList(struct ListNode* head) {
if (head == NULL || head -> next == NULL || head -> next -> next == NULL)
return;
ListNode *mid = head, *tail = head -> next;
while (tail && tail -> next) {
mid = mid -> next;
tail = tail -> next -> next;
}
reverseList(mid);
ListNode *qNode = mid -> next, *qNextNode;
mid -> next = NULL;
ListNode *preNode = head;
ListNode *curNode = preNode -> next;
while (curNode != NULL) {
preNode -> next = qNode;
qNextNode = qNode -> next;
qNode -> next = curNode;
preNode = curNode;
curNode = curNode -> next;
qNode = qNextNode;
} preNode -> next = qNode;
}

解题描述

这道题刚拿上手还是有点不知所措。想得清楚怎么画图,就是不知道怎么实现。后面才慢慢想出,在原来的链表中间的地方截断成2个链表,将后半截用带头节点链表反转的方式进行反转,之后再合并这两个量表。主要还是考验了链表的操作,包括:

  1. 快速找到链表中间节点
  2. 反转链表
  3. 链表合并

最新文章

  1. AlloyTouch Button插件-不再愁click延迟和点击态
  2. kailli linux download
  3. mysqll底层分享(一):MySQL索引背后的数据结构及算法原理
  4. 移动端:active,:hover无法很好触发动画的解决方案
  5. ubuntu 12.04 server + OPENACS(TR069)安装配置日记
  6. rsync 不能同不子级目录的问题
  7. 分享书籍[writing idiomatic python ebook] 二
  8. JAVA:数组,排序,查找<4>
  9. Tomcat 架构 (一)
  10. 李洪强iOS开发之-环信02_iOS SDK 介绍及导入
  11. log4j.propertise配置文件
  12. 64bits Python2.7.5安装numpy包
  13. java 构造函数是如何执行的
  14. MQ日常维护操作手册
  15. bzoj3223Tyvj 1729 文艺平衡树 splay
  16. Animate与transform的使用
  17. python-文件读写
  18. SSH命令行管理文件
  19. 基于UML的毕业选题系统建模研究
  20. Srt字幕文件解析

热门文章

  1. 【java并发编程实战】第六章:线程池
  2. 七天入门C++
  3. AcCoder Contest-115 D - Christmas
  4. LeetCode 81——搜索旋转排序数组 II
  5. web开发速查表(php,css,html5........)
  6. 权限管理UML设计草图
  7. Node js 安装+回调函数+事件
  8. js把字符串格式的时间转换成几秒前、几分钟前、几小时前、几天前等格式
  9. 写一篇Hook Driver.
  10. 详细介绍弹性盒模型(display:flex)