Reverse Nodes in K Group
Solution in go
func reverseKGroup(head *ListNode, k int) *ListNode {
    start := head
    end := head
    groups := make([]*ListNode, 0)

    for {
        n := k - 1

        // Move n positions for a group
        for n > 0 && end != nil {
            end = end.Next
            n--
        }

        if end == nil {
            groups = append(groups, start)
            break
        } else {
            groups = append(groups, end)
        }

        next := end.Next

        if n == 0 {
            curr := start
            var prev *ListNode

            for {
                next := curr.Next
                curr.Next = prev
                prev = curr
                curr = next

                if prev == end {
                    break
                }
            }

            start = next
            end = next
        } else {
            break
        }
    }

    for i := 0; i < len(groups) - 1; i++ {
        temp := groups[0]
        for temp.Next != nil {
            temp = temp.Next
        }
        temp.Next = groups[i+1]
    }

    return groups[0]
}
    TheDeveloperCafe © 2022-2024