XOR Linked List - Reverse a Linked List in groups of given size
Last Updated :
18 Jan, 2024
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list.
Examples:
Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3
Output: 8 < – > 6 < – > 7 < – > 3 < – > 11
Explanation:
Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6 < – > 7 < – > 11 < – > 3.
Reversing remaining nodes of the Linked List to 8 < – > 6 < – > 7 < – > 3 < – > 11.
Therefore, the required output is 8 < – > 6 < – > 7 < – > 3 < – > 11.
Input: XLL = 7 < – > 6 < – > 8 < –> 11 < – > 3 < – > 1 < – > 2 < – > 0, K = 3
Output: 8 < – > 6 < – > 7 < – > 1 < – > 3 < – > 11 < – > 0 < – > 2
Approach: The idea is to recursively reverse every K nodes of the XOR linked list in a group and connect the first node of every group of K nodes to the last node of its previous group of nodes. The recursive function is as follows:
RevInGrp(head, K, N)
{
reverse(head, min(K, N))
if (N < K) {
return head
}
head->next = RevGInGrp(next, K, N - K)
}
Follow the steps below to solve the problem:
- Reverse the first K nodes of the XOR linked list and recursively reverse the remaining nodes in a group of size K. If the count of remaining nodes is less than K, then just reverse the remaining nodes.
- Finally, connect the first node of every group to the last node of its previous group.
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
#include <inttypes.h>
using namespace std;
// Structure of a node
// in XOR linked list
struct Node {
// Stores data value
// of a node
int data;
// Stores XOR of previous
// pointer and next pointer
struct Node* nxp;
};
// Function to find the XOR of address
// of two nodes
struct Node* XOR(struct Node* a, struct Node* b)
{
return (struct Node*)((uintptr_t)(a) ^ (uintptr_t)(b));
}
// Function to insert a node with
// given value at given position
struct Node* insert(struct Node** head, int value)
{
// If XOR linked list is empty
if (*head == NULL) {
// Initialize a new Node
struct Node* node = new Node;
// Stores data value in
// the node
node->data = value;
// Stores XOR of previous
// and next pointer
node->nxp = XOR(NULL, NULL);
// Update pointer of head node
*head = node;
}
// If the XOR linked list
// is not empty
else {
// Stores the address
// of current node
struct Node* curr = *head;
// Stores the address
// of previous node
struct Node* prev = NULL;
// Initialize a new Node
struct Node* node
= new Node();
// Update curr node address
curr->nxp = XOR(node, XOR(NULL, curr->nxp));
// Update new node address
node->nxp = XOR(NULL, curr);
// Update head
*head = node;
// Update data value of
// current node
node->data = value;
}
return *head;
}
// Function to print elements of
// the XOR Linked List
void printList(struct Node** head)
{
// Stores XOR pointer
// in current node
struct Node* curr = *head;
// Stores XOR pointer of
// in previous Node
struct Node* prev = NULL;
// Stores XOR pointer of
// in next node
struct Node* next;
// Traverse XOR linked list
while (curr != NULL) {
// Print current node
cout << curr->data << " ";
// Forward traversal
next = XOR(prev, curr->nxp);
// Update prev
prev = curr;
// Update curr
curr = next;
}
}
// Reverse the linked list in group of K
struct Node* RevInGrp(struct Node** head, int K, int len)
{
// Stores head node
struct Node* curr = *head;
// If the XOR linked
// list is empty
if (curr == NULL)
return NULL;
// Stores count of nodes
// reversed in current group
int count = 0;
// Stores XOR pointer of
// in previous Node
struct Node* prev = NULL;
// Stores XOR pointer of
// in next node
struct Node* next;
// Reverse nodes in current group
while (count < K && count < len) {
// Forward traversal
next = XOR(prev, curr->nxp);
// Update prev
prev = curr;
// Update curr
curr = next;
// Update count
count++;
}
// Disconnect prev node from the next node
prev->nxp = XOR(NULL, XOR(prev->nxp, curr));
// Disconnect curr from previous node
if (curr != NULL)
curr->nxp = XOR(XOR(curr->nxp, prev), NULL);
// If the count of remaining
// nodes is less than K
if (len < K) {
return prev;
}
else {
// Update len
len -= K;
// Recursively process the next nodes
struct Node* dummy = RevInGrp(&curr, K, len);
// Connect the head pointer with the prev
(*head)->nxp = XOR(XOR(NULL, (*head)->nxp), dummy);
// Connect prev with the head
if (dummy != NULL)
dummy->nxp = XOR(XOR(dummy->nxp, NULL), *head);
return prev;
}
}
// Driver Code
int main()
{
/* Create following XOR Linked List
head-->7<–>6<–>8<–>11<–>3<–>1<–>2<–>0*/
struct Node* head = NULL;
insert(&head, 0);
insert(&head, 2);
insert(&head, 1);
insert(&head, 3);
insert(&head, 11);
insert(&head, 8);
insert(&head, 6);
insert(&head, 7);
// Function Call
head = RevInGrp(&head, 3, 8);
// Print the reversed list
printList(&head);
return (0);
}
// This code is contributed by pankajsharmagfg.
C
// C program to implement
// the above approach
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
// Structure of a node
// in XOR linked list
struct Node {
// Stores data value
// of a node
int data;
// Stores XOR of previous
// pointer and next pointer
struct Node* nxp;
};
// Function to find the XOR of address
// of two nodes
struct Node* XOR(struct Node* a,
struct Node* b)
{
return (struct Node*)((uintptr_t)(a)
^ (uintptr_t)(b));
}
// Function to insert a node with
// given value at given position
struct Node* insert(struct Node** head,
int value)
{
// If XOR linked list is empty
if (*head == NULL) {
// Initialize a new Node
struct Node* node
= (struct Node*)malloc(
sizeof(struct Node));
// Stores data value in
// the node
node->data = value;
// Stores XOR of previous
// and next pointer
node->nxp = XOR(NULL, NULL);
// Update pointer of head node
*head = node;
}
// If the XOR linked list
// is not empty
else {
// Stores the address
// of current node
struct Node* curr = *head;
// Stores the address
// of previous node
struct Node* prev = NULL;
// Initialize a new Node
struct Node* node
= (struct Node*)malloc(
sizeof(struct Node));
// Update curr node address
curr->nxp = XOR(node, XOR(NULL,
curr->nxp));
// Update new node address
node->nxp = XOR(NULL, curr);
// Update head
*head = node;
// Update data value of
// current node
node->data = value;
}
return *head;
}
// Function to print elements of
// the XOR Linked List
void printList(struct Node** head)
{
// Stores XOR pointer
// in current node
struct Node* curr = *head;
// Stores XOR pointer of
// in previous Node
struct Node* prev = NULL;
// Stores XOR pointer of
// in next node
struct Node* next;
// Traverse XOR linked list
while (curr != NULL) {
// Print current node
printf("%d ", curr->data);
// Forward traversal
next = XOR(prev, curr->nxp);
// Update prev
prev = curr;
// Update curr
curr = next;
}
}
// Reverse the linked list in group of K
struct Node* RevInGrp(struct Node** head,
int K, int len)
{
// Stores head node
struct Node* curr = *head;
// If the XOR linked
// list is empty
if (curr == NULL)
return NULL;
// Stores count of nodes
// reversed in current group
int count = 0;
// Stores XOR pointer of
// in previous Node
struct Node* prev = NULL;
// Stores XOR pointer of
// in next node
struct Node* next;
// Reverse nodes in current group
while (count < K && count < len) {
// Forward traversal
next = XOR(prev, curr->nxp);
// Update prev
prev = curr;
// Update curr
curr = next;
// Update count
count++;
}
// Disconnect prev node from the next node
prev->nxp = XOR(NULL, XOR(prev->nxp, curr));
// Disconnect curr from previous node
if (curr != NULL)
curr->nxp = XOR(XOR(curr->nxp, prev), NULL);
// If the count of remaining
// nodes is less than K
if (len < K) {
return prev;
}
else {
// Update len
len -= K;
// Recursively process the next nodes
struct Node* dummy
= RevInGrp(&curr, K, len);
// Connect the head pointer with the prev
(*head)->nxp = XOR(XOR(NULL,
(*head)->nxp),
dummy);
// Connect prev with the head
if (dummy != NULL)
dummy->nxp = XOR(XOR(dummy->nxp, NULL),
*head);
return prev;
}
}
// Driver Code
int main()
{
/* Create following XOR Linked List
head-->7<–>6<–>8<–>11<–>3<–>1<–>2<–>0*/
struct Node* head = NULL;
insert(&head, 0);
insert(&head, 2);
insert(&head, 1);
insert(&head, 3);
insert(&head, 11);
insert(&head, 8);
insert(&head, 6);
insert(&head, 7);
// Function Call
head = RevInGrp(&head, 3, 8);
// Print the reversed list
printList(&head);
return (0);
}
Java
// Java program to reverse a linked list in groups of
// given size
class LinkedList {
Node head; // head of list
/* Linked list Node*/
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;
/* Reverse first k nodes of linked list */
while (count < k && current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
/* next is now a pointer to (k+1)th node
Recursively call for the list starting from
current. And make rest of the list as next of
first node */
if (next != null)
head.next = reverse(next, k);
// prev is now head of input list
return prev;
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Function to print linked list */
void printList()
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
/* Driver program to test above functions */
public static void main(String args[])
{
LinkedList llist = new LinkedList();
/* Constructed Linked List is 1->2->3->4->5->6->
7->8->8->9->null */
llist.push(0);
llist.push(2);
llist.push(1);
llist.push(3);
llist.push(11);
llist.push(8);
llist.push(6);
llist.push(7);
llist.head = llist.reverse(llist.head, 3);
llist.printList();
}
}
/* This code is contributed by Rajat Mishra */
Python3
class LinkedList:
def __init__(self):
self.head = None
class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverse(self, head, k):
if head is None:
return None
current = head
next_node = None
prev = None
count = 0
while count < k and current is not None:
next_node = current.next
current.next = prev
prev = current
current = next_node
count += 1
if next_node is not None:
head.next = self.reverse(next_node, k)
return prev
def push(self, new_data):
new_node = self.Node(new_data)
new_node.next = self.head
self.head = new_node
def print_list(self):
temp = self.head
while temp is not None:
print(temp.data, end=" ")
temp = temp.next
print()
# Driver program to test above functions
if __name__ == "__main__":
llist = LinkedList()
# Constructed Linked List is 1->2->3->4->5->6->7->8->8->9->None
llist.push(0)
llist.push(2)
llist.push(1)
llist.push(3)
llist.push(11)
llist.push(8)
llist.push(6)
llist.push(7)
llist.head = llist.reverse(llist.head, 3)
llist.print_list()
#This code is contributed Dibyabrata Panja
C#
using System;
public class LinkedList
{
public Node head;
// Node class to represent each element in the linked list
public class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
// Function to reverse the linked list in groups of k
public Node Reverse(Node head, int k)
{
if (head == null)
return null;
Node current = head;
Node nextNode = null;
Node prev = null;
int count = 0;
// Reverse k nodes
while (count < k && current != null)
{
nextNode = current.next;
current.next = prev;
prev = current;
current = nextNode;
count++;
}
// Recursive call for the remaining nodes
if (nextNode != null)
head.next = Reverse(nextNode, k);
return prev;
}
// Function to push a new element to the linked list
public void Push(int newData)
{
Node newNode = new Node(newData);
newNode.next = head;
head = newNode;
}
// Function to print the linked list
public void PrintList()
{
Node temp = head;
while (temp != null)
{
Console.Write(temp.data + " ");
temp = temp.next;
}
Console.WriteLine();
}
// Driver program to test the functions
public static void Main()
{
LinkedList llist = new LinkedList();
// Constructed Linked List is 1->2->3->4->5->6->7->8->8->9->None
llist.Push(0);
llist.Push(2);
llist.Push(1);
llist.Push(3);
llist.Push(11);
llist.Push(8);
llist.Push(6);
llist.Push(7);
llist.head = llist.Reverse(llist.head, 3);
llist.PrintList();
}
}
JavaScript
// Node class to represent linked list nodes
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// LinkedList class
class LinkedList {
constructor() {
this.head = null;
}
// Function to reverse the linked list in groups of given size
reverse(head, k) {
if (head === null)
return null;
let current = head;
let next = null;
let prev = null;
let count = 0;
// Reverse first k nodes of linked list
while (count < k && current !== null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
// Recursively call for the list starting from current
// And make rest of the list as the next of the first node
if (next !== null)
head.next = this.reverse(next, k);
// prev is now the head of the input list
return prev;
}
// Utility function to insert a new Node at the front of the list
push(newData) {
const newNode = new Node(newData);
newNode.next = this.head;
this.head = newNode;
}
// Function to print linked list
printList() {
let temp = this.head;
while (temp !== null) {
console.log(temp.data + " ");
temp = temp.next;
}
console.log();
}
}
// Driver program
const llist = new LinkedList();
// Constructed Linked List: 1->2->3->4->5->6->7->8->9->null
llist.push(0);
llist.push(2);
llist.push(1);
llist.push(3);
llist.push(11);
llist.push(8);
llist.push(6);
llist.push(7);
// Reverse the linked list in groups of 3
llist.head = llist.reverse(llist.head, 3);
// Print the reversed linked list
llist.printList();
Time Complexity: O(N)
Auxiliary Space: O(N / K)
Similar Reads
Reverse a Linked List in groups of given size
Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed.Example: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
3 min read
Reverse a Linked List in groups of given size using Stack
Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed.Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
8 min read
Reverse a Linked List in groups of given size using Deque
Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed.Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
8 min read
Reverse a Linked List in groups of given size (Iterative Approach)
Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed.Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
10 min read
Reverse a doubly linked list in groups of K size
Given a Doubly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end should be considered as a group and must be reversed.Examples: Input: 1 <-> 2 <-> 3 <-> 4 <-
15+ min read
Reverse a doubly linked list in groups of given size | Set 2
Given a doubly-linked list containing n nodes. The problem is to reverse every group of k nodes in the list. Examples: Input: List: 10<->8<->4<->2, K=2Output: 8<->10<->2<->4 Input: List: 1<->2<->3<->4<->5<->6<->7<->8, K=3O
15+ min read
Reverse given Linked List in groups of specific given sizes
Given the linked list and an array arr[] of size N, the task is to reverse every arr[i] nodes of the list at a time (0 ⤠i < N). Note: If the number of nodes in the list is greater than the sum of array, then the remaining nodes will remain as it is. Examples: Input: head = 1->2->3->4-
8 min read
XOR linked list: Reverse last K nodes of a Linked List
Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 <â> 6 <â> 8 <â> 11 <â> 3 <â> 1, K = 3Output: 7<â>6<â>8<â>1<â>3<â>11 Input: LL: 7 <â> 6 <
14 min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are
12 min read
Javascript Program For Reversing A Linked List In Groups Of Given Size - Set 1
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,
3 min read