美文网首页
js|ListNode

js|ListNode

作者: 红酒煮咖啡 | 来源:发表于2022-09-09 18:14 被阅读0次

单链表1->2->3->4->5 变成1->5->2->4->3

//链表类似于下边这样
const head = {
    val: 1,
    next: {
      val: 2,
      next: {
        val: 3,
        next: {
          val: 4,
          next: null
        }
      }
    }
  }
const reverse = (head) =>{
    if(!head || !head.next) return head;
    if(!head.next.next){
      const temp = head.next;
      head.next.next = head;
      head.next = null
      return temp;
    }
    const temp = reverse(head.next);
    head.next.next = head;
    head.next = null
    return temp;

  }
var reorderList = function(head) {
    let current = head
    let arr = []
    while(current){
        if(current.next){
            current.next = reverse(current.next)
        }
        if(current){
            current = current.next
        }
    }
    return current
};

相关文章

网友评论

      本文标题:js|ListNode

      本文链接:https://www.haomeiwen.com/subject/qhlznrtx.html