Java Program For Reversing A Linked List In Groups Of Given Size – Set 1
Last Updated :
16 Dec, 2021
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).Â
Example:Â
Input: 1->2->3->4->5->6->7->8->NULL, K = 3Â
Output: 3->2->1->6->5->4->8->7->NULLÂ
Input: 1->2->3->4->5->6->7->8->NULL, K = 5Â
Output: 5->4->3->2->1->8->7->6->NULLÂ
Algorithm: reverse(head, k)Â
- Reverse the first sub-list of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and pointer to the previous node be prev. See this post for reversing a linked list.
- head->next = reverse(next, k) ( Recursively call for rest of the list and link the two sub-lists )
- Return prev ( prev becomes the new head of the list (see the diagrams of an iterative method of this post )
Below is image shows how the reverse function works:Â
Below is the implementation of the above approach:
Java
class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
Node reverse(Node head, int k)
{
if (head == null )
return null ;
Node current = head;
Node next = null ;
Node prev = null ;
int count = 0 ;
while (count < k &&
current != null )
{
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
if (next != null )
head.next = reverse(next, k);
return prev;
}
public void push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList()
{
Node temp = head;
while (temp != null )
{
System.out.print(temp.data + " " );
temp = temp.next;
}
System.out.println();
}
public static void main(String args[])
{
LinkedList llist = new LinkedList();
llist.push( 9 );
llist.push( 8 );
llist.push( 7 );
llist.push( 6 );
llist.push( 5 );
llist.push( 4 );
llist.push( 3 );
llist.push( 2 );
llist.push( 1 );
System.out.println( "Given Linked List" );
llist.printList();
llist.head = llist.reverse(llist.head, 3 );
System.out.println( "Reversed list" );
llist.printList();
}
}
|
Output:Â
Given Linked List
1 2 3 4 5 6 7 8 9
Reversed list
3 2 1 6 5 4 9 8 7
Complexity Analysis:Â
- Time Complexity: O(n).Â
Traversal of list is done only once and it has ‘n’ elements.
- Auxiliary Space: O(n/k).Â
For each Linked List of size n, n/k or (n/k)+1 calls will be made during the recursion.
Please refer complete article on Reverse a Linked List in groups of given size | Set 1 for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...