lc025

package
v0.0.0-...-b071cee Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2023 License: GPL-3.0 Imports: 2 Imported by: 0

README

25.K 个一组翻转链表

1. 题目描述

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

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

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

进阶:

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

示例 1:


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

示例 2:


输入: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

标签 递归 链表

2. 解题

把链表节点按照k个一组分组,使用指针head依次指向每组的头节点。这个指针每次向前移动 k 步,直至链表结尾。对于每个分组,要先判断它的长度是否大于等于k。若大于,就翻转这部分链表,否则不需要翻转。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ListNode

type ListNode struct {
	Val  int
	Next *ListNode
}

func BuildCircleListWithNoHead

func BuildCircleListWithNoHead(list []int, cursor int) *ListNode

BuildCircleListWithNoHead build a circle list, which tail point to list[cursor]

func BuildListWithHead

func BuildListWithHead(data []int) *ListNode

func BuildListWithNoHead

func BuildListWithNoHead(nums []int) *ListNode

func (*ListNode) HasCycle

func (l *ListNode) HasCycle() (bool, *ListNode)

HasCycle check if linklist has cycle structure, if not, return false, nil, if yes, return true and the cycle start node

func (*ListNode) Index

func (l *ListNode) Index(target int) *ListNode

Index return the node which value equals target

func (*ListNode) Len

func (l *ListNode) Len() int

Len return list length, when list has cycle structure, return -1

func (*ListNode) Slice

func (l *ListNode) Slice() []int

Slice return slice which contains all node's values in order.

func (*ListNode) String

func (l *ListNode) String() string

String implements Stringer interface.

func (*ListNode) Tail

func (l *ListNode) Tail() *ListNode

Tail return last list node

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL