题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import . "nc_tools"
func reverseKGroup( head *ListNode , k int ) *ListNode {
h := &ListNode{Next: head}
ret, tail := h, head
for i := 1;tail != nil;i++ {
tail = tail.Next
if i == k {
if h, i= reverse(h, tail), 0;h != nil {
tail = h.Next
}
}
}
return ret.Next
}
func reverse(head, tail * ListNode) *ListNode { // head -> 之间的节点翻转 <-tail
if head == nil {
return nil
}
p := head.Next
for ;p != nil && p.Next != nil && p.Next != tail ; {
s := p.Next
p.Next = s.Next
s.Next = head.Next
head.Next = s
}
return p
}