Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

25. K 个一组翻转链表 #56

Open
buuing opened this issue Nov 6, 2021 · 0 comments
Open

25. K 个一组翻转链表 #56

buuing opened this issue Nov 6, 2021 · 0 comments

Comments

@buuing
Copy link
Owner

buuing commented Nov 6, 2021

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

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

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

进阶:

  • 你可以设计一个只使用常数额外空间的算法来解决此问题吗?
  • 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
     

示例 1:

image

输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]

示例 2:

image

输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]

示例 3:

输入:head = [1,2,3,4,5], k = 1
输出:[1,2,3,4,5]

示例 4:

输入:head = [1], k = 1
输出:[1]

提示:

  • 列表中节点的数量在范围 sz 内
  • 1 <= sz <= 5000
  • 0 <= Node.val <= 1000
  • 1 <= k <= sz

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。




  • 普通解法
const reverseKGroup = (head, k) => {
  let curr = head, prev = head
  let i = 0, arr = []
  while (curr) {
    arr.push(curr)
    curr = curr.next
    if (++i % k === 0) {
      let h = arr.pop()
      prev.next = h
      if (i === k) head = h
      let c = h
      while (arr.length) {
        c.next = arr.pop()
        c = c.next
      }
      prev = c
      c.next = curr
    }
  }
  return head
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant