[路飞]25. k-个一组翻转链表

121 阅读1分钟

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 力扣原文链接

解题思路

假设:链表长度为7,k反转长度为2,每一轮轮反转2个,总共可以反转3轮,最后节点长度不够反转长度,不反转

假设:链表长度为4,k反转长度为2,每一轮反转2个,总共可以反转4轮

一共有两种代码,反转的思路和代码差不多,主要判断反转几轮

var reverseKGroup = function (head, k) {
  if (!head || !head.next || k === 1) return head;
  let tempNode = new ListNode(-1, head);
  let second = 1;
  let cur = head;
  //查找可反转的节点并记录
  while (cur.next) {
    second++;
    cur = cur.next;
  }
  //总共可以反转second次
  second = parseInt(second / k);
  
  let pre = tempNode;
  (cur = pre.next), (next = cur.next);
  while (second > 0) {
    second--;
    let count = 1;
    while (cur && cur.next && count < k) {
      count++;
      next = cur.next;
      cur.next = next.next;
      next.next = pre.next;
      pre.next = next;
    }
    if (cur && cur.next) {
      pre = cur;
      cur = pre.next;
      next = cur.next;
    }
  }
  return tempNode.next;
};
var reverseKGroup = function (head, k) {
  if (!head || !head.next || k === 1) return head;
  let tempNode = new ListNode(-1, head);
  let c = 0;
  let endNode = tempNode.next;
  let preNode = tempNode;
  while (endNode) {
    if (++c % k === 0) {
      preNode = reverse(preNode, endNode);
      endNode = preNode.next;
    } else {
      endNode = endNode.next;
    }
  }
  return tempNode.next;
};
var reverse = function (preNode, endnode) {
  let pre = preNode,
    cur = pre.next,
    next;
  while (next !== endnode) {
    debugger;
    next = cur.next;
    cur.next = next.next;
    next.next = pre.next;
    pre.next = next;
  }
  return cur;
};