Posts Reverse First K Nodes - LinkedList
Post
Cancel

Reverse First K Nodes - LinkedList

PROBLEM DESCRIPTION

Reverse the first K Nodes of the LinkedList.

SOLUTION

snapshot

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

    Node h1=head;
    Node t=head;
    Node h2=null;
    Node h3 = head; //We will use this at the last step to connect the K reversed Nodes with rest of the LinkedList

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

    h3.next = h1;

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