Posts Reverse a Linked List in K Groups
Post
Cancel

Reverse a Linked List in K Groups

PROBLEM DESCRIPTION

Given a singly linked list and an integer k, reverse the nodes of the list k at a time and return the modified linked list. If there are less than k size, reverse them in the output list.

snapshot

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static Node reverseListKWindowSize(Node head, int k){

    if(head == null || k==0) return null;

    Node h1=head;
    Node t=head;
    Node h2=null;
    Node h3 = head;
    int tempK = k;

    while(h1 != null && k>0){
        h1 = h1.next;
        t.next = h2;
        h2 = t;
        t = h1;
        k--;
    }

    h3.next = reverseListKWindowSize(h1, tempK);

    return h2;
}
This post is licensed under CC BY 4.0 by the author.