开发者社区> 问答> 正文

反转链表,每 k 个节点反转一次,不足 k 就保持原有顺序(哔哩哔哩)#前端面试

反转链表,每 k 个节点反转一次,不足 k 就保持原有顺序(哔哩哔哩)#前端面试

展开
收起
一月19 2020-05-23 12:53:20 2221 0
1 条回答
写回答
取消 提交回答
  • image.png 我这个是链表尾部开始的,和这个头部开始的差不多

    let a = {
      value: 1,
      next: {
        value: 2,
        next: {
          value: 3,
          next: {
            value: 4,
            next: {
              value: 5,
              next: {
                value: 6,
                next: {
                  value: 7,
                  next: {
                    value: 8,
                    next: {
    
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    
    function reverseList(_head, _k) {
     // 这个求长度可以用循环,用递归长链表容易爆栈
      let get_length = (_list) => {
        if (_list == null || _list.next == null) {
          return 0
        }
        return get_length(_list.next) + 1
      }
    
      let list_length = get_length(_head)
    
      function jump(_list, _step) {
        let _t = _list
        while (_step-- > 0) {
          _t = _t.next
        }
        return _t
      }
    
    
      function reverse(_node, _step) {
        if (_step == 0) {
          return _node
        }
        let _rt = reverse(_node.next, _step - 1)
        _node.next.next = _node
        _node.next = null
    
        return _rt
      }
    
      let _count = list_length % _k
      let _link = {
        next: _head
      }
      let _link_postion = jump(_link, _count)
      let _next_start_position = null;
      while (_count < list_length) {
        let _current_start_position = _link_postion.next
        _next_start_position = jump(_link_postion, _k + 1)
        _link_postion.next = reverse(_current_start_position, _k - 1)
        _link_postion = jump(_link_postion, _k)
        _link_postion.next = _next_start_position
        _count = _count + _k;
      }
    
      return _link.next
    }
    
    console.log(reverseList(a, 4))
    
    2020-05-23 13:20:51
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
阿里云技术面试红宝书 立即下载
超全算法笔试-模拟题精解合集 立即下载
程序员面试宝典 立即下载