Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
XOR Linked List - Reversal of a List
Next article icon

XOR linked list: Reverse last K nodes of a Linked List

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 3
Output: 7<–>6<–>8<–>1<–>3<–>11

Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1 <–> 2 <–> 0, K = 5
Output: 7<–>6<–>8<–>0<–>2<–>1<–>3<–>11

Approach: Follow the steps below to solve the given problem:

  • Reverse the given XOR Linked List.
  • Now, reverse the first K nodes of the reversed linked list.
  • After completing the above steps, reverse the linked list again to get the resultant linked list.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include<bits/stdc++.h> using namespace std;  // Structure of a node of 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 calculate Bitwise XOR of the 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 the current node         struct Node* curr = *head;          // Stores the address of the previous node         struct Node* prev = NULL;          // Initialize a new Node         struct Node* node = new Node;          // Update address of current node         curr->nxp = XOR(node, XOR(NULL, curr->nxp));          // Update address of the new node         node->nxp = XOR(NULL, curr);          // Update the head node         *head = node;          // Update the 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 the current node     struct Node* curr = *head;      // Stores XOR pointer in the previous Node     struct Node* prev = NULL;      // Stores XOR pointer in the next node     struct Node* next;      // Traverse XOR linked list     while (curr != NULL) {          // Print the current node         std::cout << curr->data << " ";          // Forward traversal         next = XOR(prev, curr->nxp);          // Update the prev pointer         prev = curr;          // Update the curr pointer         curr = next;     } }  // Function to reverse the linked list in the groups of K struct Node* reverseK(struct Node** head, int K, int len) {     struct Node* curr = *head;      // If head is NULL     if (curr == NULL)         return NULL;      // If the size of XOR linked list is less than K     else if (len < K)         return *head;     else {          int count = 0;          // Stores the XOR pointer in the previous Node         struct Node* prev = NULL;          // Stores the XOR pointer in the next node         struct Node* next;          while (count < K) {              // Forward traversal             next = XOR(prev, curr->nxp);              // Update the prev pointer             prev = curr;              // Update the curr pointer             curr = next;              // Count the number of nodes processed             count++;         }          // Remove the prev node from the next node         prev->nxp = XOR(NULL, XOR(prev->nxp, curr));          // Add the head pointer with prev         (*head)->nxp = XOR(XOR(NULL, (*head)->nxp), curr);          // Add the prev with the head         if (curr != NULL)             curr->nxp = XOR(XOR(curr->nxp, prev), *head);         return prev;     } }  // Function to reverse last K nodes of the given XOR Linked List void reverseLL(struct Node* head, int N, int K) {     // Reverse the given XOR LL     head = reverseK(&head, N, N);      // Reverse the first K nodes of     // the XOR LL     head = reverseK(&head, K, N);      // Reverse the given XOR LL     head = reverseK(&head, N, N);      // Print the final linked list     printList(&head); }  // Driver Code int main() {     // Stores number of nodes     int N = 6;      // Given XOR Linked List     struct Node* head = NULL;     insert(&head, 1);     insert(&head, 3);     insert(&head, 11);     insert(&head, 8);     insert(&head, 6);     insert(&head, 7);      int K = 3;      reverseLL(head, N, K);      return (0); }  // This code is contributed by ajaymakvana. 
C
// C program for the above approach  #include <inttypes.h> #include <stdio.h> #include <stdlib.h>  // Structure of a node // of 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 calculate // Bitwise XOR of the 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 the current node         struct Node* curr = *head;          // Stores the address         // of the previous node         struct Node* prev = NULL;          // Initialize a new Node         struct Node* node             = (struct Node*)malloc(                 sizeof(struct Node));          // Update address of current node         curr->nxp = XOR(node,                         XOR(                             NULL, curr->nxp));          // Update address of the new node         node->nxp = XOR(NULL, curr);          // Update the head node         *head = node;          // Update the 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 the current node     struct Node* curr = *head;      // Stores XOR pointer     // in the previous Node     struct Node* prev = NULL;      // Stores XOR pointer in the     // next node     struct Node* next;      // Traverse XOR linked list     while (curr != NULL) {          // Print the current node         printf("%d ", curr->data);          // Forward traversal         next = XOR(prev, curr->nxp);          // Update the prev pointer         prev = curr;          // Update the curr pointer         curr = next;     } }  // Function to reverse the linked // list in the groups of K struct Node* reverseK(struct Node** head,                       int K, int len) {     struct Node* curr = *head;      // If head is NULL     if (curr == NULL)         return NULL;      // If the size of XOR linked     // list is less than K     else if (len < K)         return *head;     else {          int count = 0;          // Stores the XOR pointer         // in the previous Node         struct Node* prev = NULL;          // Stores the XOR pointer         // in the next node         struct Node* next;          while (count < K) {              // Forward traversal             next = XOR(prev, curr->nxp);              // Update the prev pointer             prev = curr;              // Update the curr pointer             curr = next;              // Count the number of             // nodes processed             count++;         }          // Remove the prev node         // from the next node         prev->nxp = XOR(NULL,                         XOR(prev->nxp,                             curr));          // Add the head pointer with prev         (*head)->nxp = XOR(XOR(NULL,                                (*head)->nxp),                            curr);          // Add the prev with the head         if (curr != NULL)             curr->nxp = XOR(XOR(curr->nxp,                                 prev),                             *head);         return prev;     } }  // Function to reverse last K nodes // of the given XOR Linked List void reverseLL(struct Node* head,                int N, int K) {      // Reverse the given XOR LL     head = reverseK(&head, N, N);      // Reverse the first K nodes of     // the XOR LL     head = reverseK(&head, K, N);      // Reverse the given XOR LL     head = reverseK(&head, N, N);      // Print the final linked list     printList(&head); }  // Driver Code int main() {     // Stores number of nodes     int N = 6;      // Given XOR Linked List      struct Node* head = NULL;     insert(&head, 1);     insert(&head, 3);     insert(&head, 11);     insert(&head, 8);     insert(&head, 6);     insert(&head, 7);      int K = 3;      reverseLL(head, N, K);      return (0); } 
Java
// Java program for the above approach import java.util.*;  // Structure of a node of XOR Linked List class Node {     // Stores data value of a node     int data;     // Stores XOR of previous pointer and next pointer     Node npx;      // Constructor     Node(int data)     {         this.data = data;         this.npx = null;     } }  // Class for the XOR Linked List class XorLinkedList {      Node head;      XorLinkedList() { head = null; }      // Function to insert a node with given value at given     // position     void insert(int value)     {         Node node = new Node(value);         node.npx = head;         head = node;     }      // Function to print elements of the XOR Linked List     void printList()     {         // Stores XOR pointer in the current node         Node curr = head;          // Traverse XOR linked list         while (curr != null) {             // Print the current node             System.out.print(curr.data + " ");              // Update the curr pointer             curr = curr.npx;         }     }      // Function to reverse the linked list in the groups of     // K     Node reverseK(Node head, int K, int len)     {         Node curr = head;          // If head is NULL         if (curr == null)             return null;          // If the size of XOR linked list is less than K         else if (len < K)             return head;         else {             int count = 0;             // Stores the XOR pointer in the previous Node             Node prev = null;             // Stores the XOR pointer in the next node             Node next = null;             while (count < K && curr != null) {                 // Forward traversal                 next = curr.npx;                 // Update the curr.npx pointer                 curr.npx = prev;                 // Update the prev pointer                 prev = curr;                 // Update the curr pointer                 curr = next;                  // Count the number of nodes processed                 count++;             }              // // Add the prev with the head             if (curr != null)                 head.npx = curr;              // return prev             return prev;         }     }      // Function to reverse last K nodes of the given XOR     // Linked List     Node reverseLL(Node head, int N, int K)     {         // Reverse the given XOR LL         head = reverseK(head, N, N);         // Reverse the first K nodes of the XOR LL         head = reverseK(head, K, N);         // Reverse the given XOR LL         head = reverseK(head, N, N);          return head;     } }  public class GFG {     // Driver Code     public static void main(String[] args)     {         // Stores number of nodes         int N = 6;         // Given XOR Linked List         XorLinkedList xorLinkedList = new XorLinkedList();         xorLinkedList.insert(1);         xorLinkedList.insert(3);         xorLinkedList.insert(11);         xorLinkedList.insert(8);         xorLinkedList.insert(6);         xorLinkedList.insert(7);         int K = 3;         xorLinkedList.head = xorLinkedList.reverseLL(             xorLinkedList.head, N, K);         // Print the final linked list         xorLinkedList.printList();     } }  // This code is contributed by Susobhan Akhuli 
JavaScript
// JavaScript program for the above approach  // Structure of a node of XOR Linked List class Node {   constructor(data) {     this.data = data;     this.npx = null;   } }  // Class for the XOR Linked List class XorLinkedList {   constructor() {     this.head = null;   }    // Function to insert a node with given value at given   // position   insert(value) {     let node = new Node(value);     node.npx = this.head;     this.head = node;   }    // Function to print elements of the XOR Linked List   printList() {     // Stores XOR pointer in the current node     let curr = this.head;     let result = '';      // Traverse XOR linked list     while (curr != null) {       // Add the current node data to the result string       result += curr.data + " ";        // Update the curr pointer       curr = curr.npx;     }      // Print the result string     console.log(result.trim());   }    // Function to reverse the linked list in the groups of   // K   reverseK(head, K, len) {     let curr = head;      // If head is NULL     if (curr == null) return null;      // If the size of XOR linked list is less than K     else if (len < K) return head;     else {       let count = 0;       // Stores the XOR pointer in the previous Node       let prev = null;       // Stores the XOR pointer in the next node       let next = null;       while (count < K && curr != null) {         // Forward traversal         next = curr.npx;         // Update the curr.npx pointer         curr.npx = prev;         // Update the prev pointer         prev = curr;         // Update the curr pointer         curr = next;          // Count the number of nodes processed         count++;       }        // Add the prev with the head       if (curr != null) head.npx = curr;        // return prev       return prev;     }   }    // Function to reverse last K nodes of the given XOR   // Linked List   reverseLL(head, N, K) {     // Reverse the given XOR LL     head = this.reverseK(head, N, N);     // Reverse the first K nodes of the XOR LL     head = this.reverseK(head, K, N);     // Reverse the given XOR LL     head = this.reverseK(head, N, N);      return head;   } }  // Driver Code let N = 6; // Given XOR Linked List let xorLinkedList = new XorLinkedList(); xorLinkedList.insert(1); xorLinkedList.insert(3); xorLinkedList.insert(11); xorLinkedList.insert(8); xorLinkedList.insert(6); xorLinkedList.insert(7); let K = 3; xorLinkedList.head = xorLinkedList.reverseLL(   xorLinkedList.head,   N,   K ); // Print the final linked list xorLinkedList.printList(); 
Python3
# Python program for the above approach  # Structure of a node of XOR Linked List class Node:     # Constructor     def __init__(self, data):         # Stores data value of a node         self.data = data         # Stores XOR of previous pointer and next pointer         self.npx = None  # Class for the XOR Linked List class XorLinkedList:     # Constructor     def __init__(self):         self.head = None      # Function to insert a node with given value at given position     def insert(self, value):         node = Node(value)         node.npx = self.head         self.head = node      # Function to print elements of the XOR Linked List     def printList(self):         # Stores XOR pointer in the current node         curr = self.head         # Traverse XOR linked list         while curr != None:             # Print the current node             print(curr.data, end=" ")             # Update the curr pointer             curr = curr.npx      # Function to reverse the linked list in the groups of K     def reverseK(self, head, K, length):         curr = head         # If head is NULL         if curr == None:             return None         # If the size of XOR linked list is less than K         elif length < K:             return head         else:             count = 0             # Stores the XOR pointer in the previous Node             prev = None             # Stores the XOR pointer in the next node             next = None             while count < K and curr != None:                 # Forward traversal                 next = curr.npx                 # Update the curr.npx pointer                 curr.npx = prev                 # Update the prev pointer                 prev = curr                 # Update the curr pointer                 curr = next                 # Count the number of nodes processed                 count += 1             # Add the prev with the head             if curr != None:                 head.npx = curr             # return prev             return prev      # Function to reverse last K nodes of the given XOR Linked List     def reverseLL(self, head, N, K):         # Reverse the given XOR LL         head = self.reverseK(head, N, N)         # Reverse the first K nodes of the XOR LL         head = self.reverseK(head, K, N)         # Reverse the given XOR LL         head = self.reverseK(head, N, N)         return head  # Driver Code if __name__ == "__main__":     # Stores number of nodes     N = 6     # Given XOR Linked List     xorLinkedList = XorLinkedList()     xorLinkedList.insert(1)     xorLinkedList.insert(3)     xorLinkedList.insert(11)     xorLinkedList.insert(8)     xorLinkedList.insert(6)     xorLinkedList.insert(7)     K = 3     xorLinkedList.head = xorLinkedList.reverseLL(xorLinkedList.head, N, K)     # Print the final linked list     xorLinkedList.printList()  # This code is contributed by Susobhan Akhuli 

Output
7 6 8 1 3 11      

Time Complexity: O(N), as we are using a loop to traverse N times, where N is the length of the linked list.
Auxiliary Space: O(1), as we are not using any extra space.



Next Article
XOR Linked List - Reversal of a List

D

debarpan_bose_chowdhury
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Linked List
  • Bitwise-XOR
  • Reverse
Practice Tags :
  • Bit Magic
  • Linked List
  • Reverse

Similar Reads

  • XOR Linked List: Remove last node of the Linked List
    Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is empt
    15+ min read
  • XOR Linked List - Reverse a Linked List in groups of given size
    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)
    13 min read
  • XOR Linked List - Reversal of a List
    Given a XOR linked list, the task is to reverse the XOR linked list. Examples: Input: 4 <–> 7 <–> 9 <–> 7Output: 7 <–> 9 <–> 7 <–> 4Explanation:Reversing the linked list modifies the XOR linked list to 7 <–> 9 <–> 7 <–> 4. Input: 2 <-> 5
    12 min read
  • Reverse each word in a linked list node
    Given a linked list of strings, we need to reverse each word of the string in the given linked list. Examples: Input: geeksforgeeks a computer science portal for geeks Output: skeegrofskeeg a retupmoc ecneics latrop rof skeeg Input: Publish your own articles on geeksforgeeks Output: hsilbuP ruoy nwo
    6 min read
  • Reverse alternate K nodes in a Singly Linked List
    Given a linked list, The task is to reverse alternate k nodes. If the number of nodes left at the end of the list is fewer than k, reverse these remaining nodes or leave them in their original order, depending on the alternation pattern. Example: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -
    15+ min read
  • XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
    In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert
    10 min read
  • An interesting method to print reverse of a linked list
    We are given a linked list, we need to print the linked list in reverse order.Examples: Input : list : 5-> 15-> 20-> 25 Output : Reversed Linked list : 25-> 20-> 15-> 5Input : list : 85-> 15-> 4-> 20 Output : Reversed Linked list : 20-> 4-> 15-> 85Input : list : 8
    7 min read
  • Convert Singly Linked List to XOR Linked List
    Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a
    9 min read
  • Can we reverse a linked list in less than O(n)?
    It is not possible to reverse a simple singly linked list in less than O(n). A simple singly linked list can only be reversed in O(n) time using recursive and iterative methods. A doubly linked list with head and tail pointers while only requiring swapping the head and tail pointers which require le
    1 min read
  • Insert Node at the End of a Linked List
    Given a linked list, the task is to insert a new node at the end of the linked list. Examples: Input: LinkedList = 2 -> 3 -> 4 -> 5, NewNode = 1Output: LinkedList = 2 -> 3 -> 4 -> 5 -> 1 Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1 Approach:  Inserting at the end
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences