Table of Contents
Reverse Nodes in k-Group
Logic
- Use mind to make it simple
- Try to reuse existing code
- Calculate number of iterations required with given total length and k
- call reverseBetween(head *ListNode, leftIndex int, rightIndex int) for those many iterations
- i.e. reuse function implement in reverse-linked-list-ii
Golang Solution
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseKGroup(head *ListNode, k int) *ListNode {
current := head
count := 0
for current != nil {
current = current.Next
count++
}
fmt.Printf("Total nodes : %d\n", count)
iterations := count / k
fmt.Printf("iterations : %d\n", iterations)
leftIndex, rightIndex := 1, k
for i := 1; i <= iterations; i++ {
fmt.Printf("leftIndex=%d, rightIndex=%d\n", leftIndex, rightIndex)
head = reverseBetween(head, leftIndex, rightIndex)
leftIndex += k
rightIndex += k
}
return head
}
func reverseBetween(head *ListNode, leftIndex int, rightIndex int) *ListNode {
//edge case
if leftIndex == rightIndex {
return head
}
var leftPrev *ListNode
current := head
//input is started from 1
// so use staring point as 1 to make it simple in iterations
for i := 1; i <= leftIndex-1; i++ {
leftPrev = current
current = current.Next
}
oldLeftHead := current
//fmt.Printf("oldLeftHead=%d\n", oldLeftHead.Val)
var prev *ListNode
for j := 1; j <= rightIndex-leftIndex+1; j++ {
next := current.Next
current.Next = prev
prev = current
current = next
}
oldLeftHead.Next = current
if leftPrev == nil {
return prev
}
leftPrev.Next = prev
return head
}
Output
Input
head = [1,2,3,4,5]
k = 2
Stdout
Total nodes : 5
iterations : 2
leftIndex=1, rightIndex=2
leftIndex=3, rightIndex=4
Output
[2,1,4,3,5]
Please visit https: https://codeandalgo.com for more such contents
Leave a Reply