思路:
1.递归,每次处理k个,不足k个不处理
2.对k个的处理用reverse进行
3.reverse实际上由k+1个,通过prev,first和temp来逐次挪动
src
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseKGroup(head *ListNode, k int) *ListNode { node := head for i := 0; i < k; i++ { if node == nil { return head } node = node.Next } newHead := reverse(head, node) head.Next = reverseKGroup(node, k) return newHead } func reverse(first, last *ListNode) *ListNode { prev := last for first != last { tmp := first.Next first.Next = prev prev = first first = tmp } return prev }
总结:
思路get了,细节没get