Java Program For Reversing A Linked List In Groups Of Given Size- Set 2
Last Updated :
25 Oct, 2022
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).
Examples:
Input: 1->2->3->4->5->6->7->8->NULL and k = 3
Output: 3->2->1->6->5->4->8->7->NULL.
Input: 1->2->3->4->5->6->7->8->NULL and k = 5
Output: 5->4->3->2->1->8->7->6->NULL.
We have already discussed its solution in below post
Reverse a Linked List in groups of given size | Set 1
In this post, we have used a stack which will store the nodes of the given linked list. Firstly, push the k elements of the linked list in the stack. Now pop elements one by one and keep track of the previously popped node. Point the next pointer of prev node to top element of stack. Repeat this process, until NULL is reached.
This algorithm uses O(k) extra space.
Java
import java.util.*;
class GfG
{
static class Node
{
int data;
Node next;
}
static Node head = null ;
static Node Reverse(Node head, int k)
{
Stack<Node> mystack =
new Stack<Node> ();
Node current = head;
Node prev = null ;
while (current != null )
{
int count = 0 ;
while (current != null && count < k)
{
mystack.push(current);
current = current.next;
count++;
}
while (mystack.size() > 0 )
{
if (prev == null )
{
prev = mystack.peek();
head = prev;
mystack.pop();
}
else
{
prev.next = mystack.peek();
prev = prev.next;
mystack.pop();
}
}
}
prev.next = null ;
return head;
}
static void push( int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head;
head = new_node;
}
static void printList(Node node)
{
while (node != null )
{
System.out.print(node.data + " " );
node = node.next;
}
}
public static void main(String[] args)
{
push( 9 );
push( 8 );
push( 7 );
push( 6 );
push( 5 );
push( 4 );
push( 3 );
push( 2 );
push( 1 );
System.out.println(
"Given linked list " );
printList(head);
head = Reverse(head, 3 );
System.out.println();
System.out.println(
"Reversed Linked list " );
printList(head);
}
}
|
Output:
Given Linked List
1 2 3 4 5 6 7 8 9
Reversed list
3 2 1 6 5 4 9 8 7
Please refer complete article on Reverse a Linked List in groups of given size | Set 2 for more details!
Share your thoughts in the comments
Please Login to comment...