Reverse a singly Linked List in groups of given size | Set 3
Last Updated :
27 Jan, 2023
Given a singly linked list and an integer K, the task is to reverse every K nodes of the given linked list.
Examples:
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> NULL, K = 3
Output: 3 2 1 6 5 4 8 7
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> NULL, K = 5
Output: 5 4 3 2 1 8 7 6
Approach: Two different approaches to solve this problem have been discussed in Set 1 and Set 2 of this article. In this article, an approach based on deque will be discussed.
- Create a deque.
- Store the address of the first k nodes in the deque.
- Pop first and the last value from the deque and swap the data values at those addresses.
- Repeat step 3 till the deque is not empty.
- Repeat step 2 for the next k nodes and till the end of the linked list is not reached.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
struct node* next;
};
void push(node** head_ref, int new_data)
{
node* new_node = new node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(node* head)
{
while (head != NULL) {
cout << head->data << " " ;
head = head->next;
}
}
struct node* reverse( struct node* head, int k)
{
if (head == NULL)
return head;
deque<node*> q;
node* current = head;
int i;
while (current != NULL) {
i = 1;
while (i <= k) {
if (current == NULL)
break ;
q.push_back(current);
current = current->next;
i++;
}
while (!q.empty()) {
node* front = q.front();
node* last = q.back();
swap(front->data, last->data);
if (!q.empty())
q.pop_front();
if (!q.empty())
q.pop_back();
}
}
return head;
}
int main()
{
node* head = NULL;
push(&head, 10);
push(&head, 9);
push(&head, 8);
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
int k = 2;
head = reverse(head, k);
printList(head);
return 0;
}
|
Java
import java.util.*;
class LinkedList{
static Node head;
static class Node
{
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
public void push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList(Node node)
{
while (node != null )
{
System.out.print(node.data + " " );
node = node.next;
}
}
Node reverse(Node head, int k)
{
if (head == null )
return head;
Deque<Node> q = new ArrayDeque<Node>();
Node current = head;
int i;
while (current != null )
{
i = 1 ;
while (i <= k)
{
if (current == null )
break ;
q.addLast(current);
current = current.next;
i++;
}
while (!q.isEmpty())
{
Node front = q.peekFirst();
Node last = q.peekLast();
int temp = front.data;
front.data = last.data;
last.data = temp;
if (!q.isEmpty())
q.removeFirst();
if (!q.isEmpty())
q.removeLast();
}
}
return head;
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.push( 10 );
list.push( 9 );
list.push( 8 );
list.push( 7 );
list.push( 6 );
list.push( 5 );
list.push( 4 );
list.push( 3 );
list.push( 2 );
list.push( 1 );
int k = 2 ;
head = list.reverse(head, k);
list.printList(head);
}
}
|
Python3
class Node:
def __init__( self ):
self .data = 0
self . next = None
def push(head_ref, new_data):
new_node = Node()
new_node.data = new_data
new_node. next = (head_ref)
(head_ref) = new_node
return head_ref
def printList( head):
while (head ! = None ) :
print ( head.data, end = " " )
head = head. next
def reverse( head, k):
if (head = = None ):
return head
q = []
current = head
i = 0
while (current ! = None ) :
i = 1
while (i < = k) :
if (current = = None ):
break
q.append(current)
current = current. next
i = i + 1
while ( len (q) > 0 ):
front = q[ - 1 ]
last = q[ 0 ]
temp = front.data
front.data = last.data
last.data = temp
if ( len (q) > 0 ):
q.pop()
if ( len (q)):
q.pop( 0 )
return head
head = None
head = push(head, 10 )
head = push(head, 9 )
head = push(head, 8 )
head = push(head, 7 )
head = push(head, 6 )
head = push(head, 5 )
head = push(head, 4 )
head = push(head, 3 )
head = push(head, 2 )
head = push(head, 1 )
k = 2
head = reverse(head, k)
printList(head)
|
C#
using System;
using System.Collections.Generic;
class List{
static Node head;
class Node
{
public int data;
public Node next;
public Node( int d)
{
data = d;
next = null ;
}
}
public void Push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList(Node node)
{
while (node != null )
{
Console.Write(node.data + " " );
node = node.next;
}
}
Node reverse(Node head, int k)
{
if (head == null )
return head;
List<Node> q = new List<Node>();
Node current = head;
int i;
while (current != null )
{
i = 1;
while (i <= k)
{
if (current == null )
break ;
q.Add(current);
current = current.next;
i++;
}
while (q.Count != 0)
{
Node front = q[0];
Node last = q[q.Count - 1];
int temp = front.data;
front.data = last.data;
last.data = temp;
if (q.Count != 0)
q.RemoveAt(0);
if (q.Count != 0)
q.RemoveAt(q.Count - 1);
}
}
return head;
}
public static void Main(String[] args)
{
List list = new List();
list.Push(10);
list.Push(9);
list.Push(8);
list.Push(7);
list.Push(6);
list.Push(5);
list.Push(4);
list.Push(3);
list.Push(2);
list.Push(1);
int k = 2;
head = list.reverse(head, k);
list.printList(head);
}
}
|
Javascript
<script>
var head = null ;
class Node
{
constructor(d)
{
this .data = d;
this .next = null ;
}
}
function Push(new_data)
{
var new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
function printList(node)
{
while (node != null )
{
document.write(node.data + " " );
node = node.next;
}
}
function reverse(head, k)
{
if (head == null )
return head;
var q = [];
var current = head;
var i;
while (current != null )
{
i = 1;
while (i <= k)
{
if (current == null )
break ;
q.push(current);
current = current.next;
i++;
}
while (q.length != 0)
{
var front = q[0];
var last = q[q.length - 1];
var temp = front.data;
front.data = last.data;
last.data = temp;
if (q.Count != 0)
q.shift();
if (q.Count != 0)
q.pop();
}
}
return head;
}
Push(10);
Push(9);
Push(8);
Push(7);
Push(6);
Push(5);
Push(4);
Push(3);
Push(2);
Push(1);
var k = 2;
head = reverse(head, k);
printList(head);
</script>
|
Output:
2 1 4 3 6 5 8 7 10 9
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...