博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
143. Reorder List
阅读量:6946 次
发布时间:2019-06-27

本文共 1295 字,大约阅读时间需要 4 分钟。

/**

143. Reorder List

https://leetcode.com/problems/reorder-list/description/

* @param {ListNode} head

* @return {void} Do not return anything, modify head in-place instead.
*/

var reorderList = function (head) {

  if (head==null || head.next==null)
    return;
  //1.find the middle of list
  let middle = findMiddle(head);
  let secondHead = middle.next;
  
  middle.next = null;//断开中点和后一段
  //2.reserve it
  let reverseSecondHead = reverseLinkedList(secondHead);
  //3.merge two list by items one by one
  return mergeLinkedList(head,reverseSecondHead);
};

var findMiddle = function (head) {

  let slow = head, fast = head;
  while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
  }
  return slow;
};

var reverseLinkedList = function (head) {

  let prev = null;
  let next = null;
  let current = head;
  while (current != null) {
    next = current.next;
    current.next = prev;//point to prve
    prev = current;
    current = next;
  }
  return prev;
};

var mergeLinkedList = function (node1,node2) {

  //将第二个链表的元素间隔地插入第一个链表中
  let cur = node1;
  while (node2!=null){
    let temp = node2.next;
    node2.next = cur.next;
    cur.next = node2;
    cur = cur.next.next;
    node2 = temp;
  }
};

转载于:https://www.cnblogs.com/johnnyzhao/p/10204388.html

你可能感兴趣的文章
Java中的位运算
查看>>
java连接mysql的一个小例子
查看>>
laravel queue 修改之后不生效的坑
查看>>
[USACO07JAN]Balanced Lineup
查看>>
[入门OJ3876]怎样学习哲学
查看>>
陶哲軒實分析 習題3.6.9
查看>>
Python国内豆瓣源
查看>>
html页面的局部刷新
查看>>
C#不常见的语法
查看>>
[摘录]高效人士七习惯—以终为始原则
查看>>
Office Visio简介
查看>>
[摘录]第4章 不道德的谈判策略
查看>>
mvc 截取上传图片做头像,自动生成不同小尺寸缩略图
查看>>
微信 登录 Scope 参数错误或没有 Scope 权限
查看>>
几个好用的javascript插件介绍
查看>>
【JDK1.8】JDK1.8集合源码阅读——HashMap
查看>>
47.论文网站监控采集数据源及功能结构图
查看>>
PCI Express(一)- Connector
查看>>
Puzzle, ACM/ICPC World Finals 1993, UVa227
查看>>
SecureCRT乱码
查看>>