25. Reverse Nodes in k-Group #
Problem #
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list’s nodes, only nodes itself may be changed.
Problem Summary #
Reverse the linked list in groups of every K elements. If there are not K elements, do not reverse them.
Solution Approach #
This problem is an enhanced version of problem 24. Problem 24 reverses the linked list by swapping every two adjacent elements. Problem 25 requires reversing every k adjacent elements in the linked list; problem 24 is equivalent to the special case where k = 2.
Code #
package leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseKGroup(head *ListNode, k int) *ListNode {
node := head
for i := 0; i < k; i++ {
if node == nil {
return head
}
node = node.Next
}
newHead := reverse(head, node)
head.Next = reverseKGroup(node, k)
return newHead
}
func reverse(first *ListNode, last *ListNode) *ListNode {
prev := last
for first != last {
tmp := first.Next
first.Next = prev
prev = first
first = tmp
}
return prev
}