[25] K 个一组翻转链表

复制代码
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var reverseKGroup = function (head, k) {
  if (k === 1 || k === 0 || head === null || head.next === null) {
    return head;
  }
  // 定义一个保护节点  
  let protect = new ListNode(0, null);
  let last = protect;
  let nextGroupStart = null;

  // 反转一串链表,前一个链表的结尾 + 反转本身 + 后一个链表的开始  
  while (head !== null) {
    // 获取最后一个节点,用于反转  
    let end = getEnd(head, k);
    // 如果到了最后不够了,保持原有顺序,直接返回即可  
    if (end === null) {
      break;
    }
    // 记录后一个链表的开始  
    nextGroupStart = end.next;

    // 反转本身,head到end反转  
    let reversed = reverseList(head, end);
    // 子链表的开头(现在的end)和上一个链表结尾结合  
    last.next = reversed;
    // 子链表的结尾(现在的head)和下一个链表开始结合  
    head.next = nextGroupStart;

    // 当前结尾下一个循环时已成上一个链表的结尾(现在的head)  
    last = head;
    // 让下一个子链表开始处理吧  
    head = nextGroupStart;
  }
  return protect.next;
}

// 找到最后一个节点,返回null说明最后已经不够k个了  
const getEnd = function (head, k) {
  let index = 1;
  while (head !== null) {
    head = head.next;
    if (++index === k) {
      return head;
    }
  }
  return null; // or head, depending on how you want to handle it  
}

// 反转head-end之间的链表  
const reverseList = function (head, end) {
  if (head === null || head.next === null) {
    return head;
  }

  let next = head.next;
  head.next = null;

  let p;
  let current = head;
  let nextNode = next;
  while (nextNode !== null && current !== end) {
    p = nextNode.next;
    nextNode.next = current;
    current = nextNode;
    nextNode = p;
  }
  return current; // could return 'head' if you want to maintain the original 'head' pointer, but it's not necessary since we know the new head will be the current node at this point anyway. (returns head if head === end or head === null)  
}
复制代码

 

posted @   人恒过  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示