25. K 个一组翻转链表
面试真的碰到了,可惜没a出来。
没啥特殊的算法,就是很难绕出来感觉。
/*** Definition for singly-linked list.* type ListNode struct {* Val int* Next *ListNode* }*/
func reverseKGroup(head *ListNode, k int) *ListNode {hair := &ListNode{Next : head}pre := hairfor head != nil{tail := prefor i := 0; i < k; i++{tail = tail.Nextif tail == nil{return hair.Next}}nex := tail.Nexthead, tail = newchange(head, tail)pre.Next = headtail.Next = nexpre = tailhead = tail.Next}return hair.Next
}
func newchange(head, tail *ListNode)(*ListNode, *ListNode){prev := tail.Nextp := headfor prev != tail{nex := p.Nextp.Next = prevprev = pp = nex}return tail, head
}