Skip to content

Commit

Permalink
Create 0025-reverse-nodes-in-k-group.go
Browse files Browse the repository at this point in the history
  • Loading branch information
AP-Repositories authored Jan 1, 2023
1 parent 0cb22b5 commit 604be10
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions go/0025-reverse-nodes-in-k-group.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
func reverseKGroup(head *ListNode, k int) *ListNode {
dummy := &ListNode{Val: 0, Next: head}
groupPrev := dummy

for true {
kth := getKth(groupPrev, k)
if kth == nil {
break;
}
groupNext := kth.Next

// reverse group
prev, curr := kth.Next, groupPrev.Next
for curr != groupNext {
tmp := curr.Next
curr.Next = prev
prev = curr
curr = tmp
}

tmp := groupPrev.Next
groupPrev.Next = kth
groupPrev = tmp
}
return dummy.Next
}

func getKth(curr *ListNode, k int) *ListNode {
for curr != nil && k > 0 {
curr = curr.Next
k -= 1
}
return curr
}

0 comments on commit 604be10

Please sign in to comment.