Alexander Obregon's Substack

Java LeetCode Solutions

LeetCode #25: Reverse Nodes in k-Group — Solved in Java

Stack Based Groups and In Place Pointer Flips

Alexander Obregon's avatar
Alexander Obregon
Oct 10, 2025
∙ Paid
LeetCode Logo
Image Source

LeetCode’s Reverse Nodes in k-Group problem takes a linked list and asks for sections of k nodes to be flipped at a time. The pattern continues through the list, reversing each complete group while leaving any leftover nodes untouched. It’s a step up from a regular list reversal because it forces you to handle multiple boundaries while keeping the list connected through every change. Small details like how you identify a full group or reconnect the ends make all the difference between a working solution and one that loses track of nodes.

Thinking about this problem in Java means focusing on how references move. Every reversal comes down to carefully managing which node points where and making sure nothing gets lost as links are reassigned. The best mindset is to break the problem into sections that repeat: find a group, reverse it, reconnect it, and move on. When that pattern feels natural, the solution becomes a rhythm of pointer movement rather than a complex problem to untangle.

LeetCode: Reverse Nodes in k-Group

Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Example 2:

Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]

Constraints:

  • The number of nodes in the list is n.

  • 1 <= k <= n <= 5000

  • 0 <= Node.val <= 1000

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

Solution 1: Stack Based Groups

This method uses a stack to reverse nodes in fixed-size groups. Each set of k nodes is pushed onto the stack and then popped to rebuild that section in reverse order before moving to the next. It keeps the logic simple and reads naturally while still following how group reversals work step by step.

Keep reading with a 7-day free trial

Subscribe to Alexander Obregon's Substack to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Alexander Obregon · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for great culture