码迷,mamicode.com
首页 > Web开发 > 详细

js 单链表的反转

时间:2020-04-23 20:47:18      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:def   head   col   sel   反转   one   code   controls   node   

 思路:

  1. 递归的基线条件:遍历到末节点(node.next === null)
  2. 递归的递归条件:node.next !== null
  3. 当遇到末节点时,返回末节点,末节点的next接受上一个head,返回前一节的,继续下去
  4. 考虑特殊情况:undefined和null
var reverseList = function (head) {
  // 闭包
  if (head === undefined || head === null) return null;
  var originalHead = head;
  var reverseHead;

  var reverse = function (head) {
    if (head.next === null) {
      reverseHead = head;
      return head;
    } else {
      var node = reverse(head.next);
      node.next = head;
      if (originalHead === head) {
        head.next = null;
        return reverseHead;
      } else {
        return head;
      }
    }
  }

  return reverse(head)
}

 

js 单链表的反转

标签:def   head   col   sel   反转   one   code   controls   node   

原文地址:https://www.cnblogs.com/ajaxkong/p/12041767.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!