XOR Linked List β Find Nth Node from the end
Given a XOR linked list and an integer N, the task is to print the Nth node from the end of the given XOR linked list.
Examples:
Input: 4 β> 6 β> 7 β> 3, N = 1
Output: 3
Explanation: 1st node from the end is 3.
Input: 5 β> 8 β> 9, N = 4
Output: Wrong Input
Explanation: The given Xor Linked List contains only 3 nodes.
Approach: Follow the steps below to solve the problem:
- Traverse the first N nodes of the Linked List using a pointer, say curr.
- Use another pointer, say curr1, and traverse the linked list incrementing curr and curr1 by a node after every iteration.
- Iterate until the pointer curr exceeds the end of the List, i.e.NULL. Once reached, print the value of the node curr1 as the required answer.
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 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; } } struct Node* NthNode( struct Node** head, int N) { int count = 0; // Stores XOR pointer // in current node struct Node* curr = *head; struct Node* curr1 = *head; // Stores XOR pointer of // in previous Node struct Node* prev = NULL; struct Node* prev1 = NULL; // Stores XOR pointer of // in next node struct Node* next; struct Node* next1; while (count < N && curr != NULL) { // Forward traversal next = XOR(prev, curr->nxp); // Update prev prev = curr; // Update curr curr = next; count++; } if (curr == NULL && count < N) { cout << "Wrong Input\n" ; return ( uintptr_t )0; } else { while (curr != NULL) { // Forward traversal next = XOR(prev, curr->nxp); next1 = XOR(prev1, curr1->nxp); // Update prev prev = curr; prev1 = curr1; // Update curr curr = next; curr1 = next1; } cout << curr1->data << " " ; } } // 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); NthNode(&head, 3); return (0); } |
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 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; } } struct Node* NthNode( struct Node** head, int N) { int count = 0; // Stores XOR pointer // in current node struct Node* curr = *head; struct Node* curr1 = *head; // Stores XOR pointer of // in previous Node struct Node* prev = NULL; struct Node* prev1 = NULL; // Stores XOR pointer of // in next node struct Node* next; struct Node* next1; while (count < N && curr != NULL) { // Forward traversal next = XOR(prev, curr->nxp); // Update prev prev = curr; // Update curr curr = next; count++; } if (curr == NULL && count < N) { printf ( "Wrong Input" ); return ( uintptr_t )0; } else { while (curr != NULL) { // Forward traversal next = XOR(prev, curr->nxp); next1 = XOR(prev1, curr1->nxp); // Update prev prev = curr; prev1 = curr1; // Update curr curr = next; curr1 = next1; } printf ( "%d" , curr1->data); } } // 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); NthNode(&head, 3); return (0); } |
Java
import java.util.*; // Structure of a node in XOR linked list class Node { int value; int npx; Node( int value) { this .value = value; this .npx = 0 ; } } // XorLinkedList class class XorLinkedList { private Node head; private Node tail; private List<Node> nodes; // Constructor public XorLinkedList() { this .head = null ; this .tail = null ; this .nodes = new ArrayList<>(); } // Function to insert a node with given value at the beginning public void insert( int value) { // Initialize a new Node Node node = new Node(value); // Check If XOR linked list is empty if (head == null ) { // Update pointer of head node head = node; // Update pointer of tail node tail = node; } else { // Update curr node address head.npx = System.identityHashCode(node) ^ head.npx; // Update new node address node.npx = System.identityHashCode(head); // Update head head = node; } // push node nodes.add(node); } // Method to get length of linked list public int length() { if (!isEmpty()) { int prevId = 0 ; Node node = head; int nextId = 1 ; int count = 1 ; while (nextId != 0 ) { nextId = prevId ^ node.npx; if (nextId != 0 ) { prevId = System.identityHashCode(node); node = typeCast(nextId); count++; } else { return count; } } } else { return 0 ; } return 0 ; } // Method to get the Nth node value public void nthNode( int N) { int count = 1 ; int prevId = 0 ; int prev1Id = 0 ; Node node = head; Node node1 = head; int nextId = 1 ; int next1Id = 1 ; while (nextId != 0 && count < N) { nextId = prevId ^ node.npx; if (nextId != 0 ) { prevId = System.identityHashCode(node); node = typeCast(nextId); count++; } else { System.out.println( "Wrong Input" ); return ; } } nextId = prevId ^ node.npx; prevId = System.identityHashCode(node); node = typeCast(nextId); if (nextId == 0 && count < N) { System.out.println( "Wrong Input" ); return ; } while (nextId != 0 ) { nextId = prevId ^ node.npx; next1Id = prev1Id ^ node1.npx; if (nextId != 0 ) { prevId = System.identityHashCode(node); node = typeCast(nextId); } if (nextId != 0 ) { prev1Id = System.identityHashCode(node1); node1 = typeCast(next1Id); } } node1 = typeCast(next1Id); System.out.println(node1.value); } // Function to print elements of the XOR Linked List public void printList() { if (head != null ) { int prevId = 0 ; Node node = head; int nextId = 1 ; System.out.print(node.value + " " ); while (nextId != 0 ) { nextId = prevId ^ node.npx; if (nextId != 0 ) { prevId = System.identityHashCode(node); node = typeCast(nextId); System.out.print(node.value + " " ); } else { return ; } } } } // Method to check if the linked list is empty or not public boolean isEmpty() { return head == null ; } // Method to return a new instance of type private Node typeCast( int id) { for (Node n : nodes) { if (System.identityHashCode(n) == id) { return n; } } return null ; } } // Main class public class Main { public static void main(String[] args) { // Create XOR linked list XorLinkedList xorLinkedList = new XorLinkedList(); // Insert elements into XOR linked list xorLinkedList.insert( 0 ); xorLinkedList.insert( 2 ); xorLinkedList.insert( 1 ); xorLinkedList.insert( 3 ); xorLinkedList.insert( 11 ); xorLinkedList.insert( 8 ); xorLinkedList.insert( 6 ); xorLinkedList.insert( 7 ); // Get the Nth node value xorLinkedList.nthNode( 3 ); } } |
C#
// C# program for the above approach using System; using System.Collections.Generic; using System.Runtime.CompilerServices; // Structure of a node in XOR linked list class Node { public int value; public int npx; public Node( int value) { this .value = value; this .npx = 0; } } // XorLinkedList class class XorLinkedList { private Node head; private List<Node> nodes; // Constructor public XorLinkedList() { this .head = null ; this .nodes = new List<Node>(); } // Function to insert a node with given value at the // beginning public void Insert( int value) { // Initialize a new Node Node node = new Node(value); // Check If XOR linked list is empty if (head == null ) { // Update pointer of head node head = node; } else { // Update curr node address head.npx = RuntimeHelpers.GetHashCode(node) ^ head.npx; // Update new node address node.npx = RuntimeHelpers.GetHashCode(head); // Update head head = node; } // push node nodes.Add(node); } // Method to get length of linked list public int Length() { if (!IsEmpty()) { int prevId = 0; Node node = head; int nextId = 1; int count = 1; while (nextId != 0) { nextId = prevId ^ node.npx; if (nextId != 0) { prevId = RuntimeHelpers.GetHashCode(node); node = TypeCast(nextId); count++; } else { return count; } } } else { return 0; } return 0; } // Method to get the Nth node value public void NthNode( int N) { int count = 1; int prevId = 0; int prev1Id = 0; Node node = head; Node node1 = head; int nextId = 1; int next1Id = 1; while (nextId != 0 && count < N) { nextId = prevId ^ node.npx; if (nextId != 0) { prevId = RuntimeHelpers.GetHashCode(node); node = TypeCast(nextId); count++; } else { Console.WriteLine( "Wrong Input" ); return ; } } nextId = prevId ^ node.npx; prevId = RuntimeHelpers.GetHashCode(node); node = TypeCast(nextId); if (nextId == 0 && count < N) { Console.WriteLine( "Wrong Input" ); return ; } while (nextId != 0) { nextId = prevId ^ node.npx; next1Id = prev1Id ^ node1.npx; if (nextId != 0) { prevId = RuntimeHelpers.GetHashCode(node); node = TypeCast(nextId); } if (nextId != 0) { prev1Id = RuntimeHelpers.GetHashCode(node1); node1 = TypeCast(next1Id); } } node1 = TypeCast(next1Id); Console.WriteLine(node1.value); } // Function to print elements of the XOR Linked List public void PrintList() { if (head != null ) { int prevId = 0; Node node = head; int nextId = 1; Console.Write(node.value + " " ); while (nextId != 0) { nextId = prevId ^ node.npx; if (nextId != 0) { prevId = RuntimeHelpers.GetHashCode(node); node = TypeCast(nextId); Console.Write(node.value + " " ); } else { return ; } } } } // Method to check if the linked list is empty or not public bool IsEmpty() { return head == null ; } // Method to return a new instance of type private Node TypeCast( int id) { foreach (Node n in nodes) { if (RuntimeHelpers.GetHashCode(n) == id) { return n; } } return null ; } } // Main class public class GFG { public static void Main( string [] args) { // Create XOR linked list XorLinkedList xorLinkedList = new XorLinkedList(); // Insert elements into XOR linked list xorLinkedList.Insert(0); xorLinkedList.Insert(2); xorLinkedList.Insert(1); xorLinkedList.Insert(3); xorLinkedList.Insert(11); xorLinkedList.Insert(8); xorLinkedList.Insert(6); xorLinkedList.Insert(7); // Get the Nth node value xorLinkedList.NthNode(3); } } // This code is contributed by Susobhan Akhuli |
Javascript
// Javascript program for the above approach // Structure of a node in XOR linked list class Node { constructor(d) { this .data = d; this .npx = null ; } } // XorLinkedList class class XorLinkedList { // constructor constructor() { this .head = null ; } // Function to insert a node with given value at given position insert(data) { // Initialize a new Node const newNode = new Node(data); newNode.npx = this .head; this .head = newNode; } // method to get length of linked list length() { let count = 0; let nextId = this .head; while (nextId!== null ) { nextId = nextId.npx; count += 1; } return count; } // Method to get the Nth node data nthNode(N) { let count = this .length(); if (N > count){ console.log( "Wrong Input" ); return ; } count -= N; let nextId = this .head; while (count > 0) { nextId = nextId.npx; count-=1; } console.log(nextId.data); } // Function to print elements of the XOR Linked List printList() { let temp = this .head; while (temp !== null ) { console.log(temp.data + " " ); temp = temp.npx; } console.log(); } // method to check if the linked list is empty or not isEmpty(nod) { if (nod === null ) { return true ; } return false ; } } // Create XOR linked list const head = new XorLinkedList(); // Insert elements into XOR linked list head.insert(0); head.insert(2); head.insert(1); head.insert(3); head.insert(11); head.insert(8); head.insert(6); head.insert(7); // Get the Nth node data head.nthNode(3); // This code is contributed by Susobhan Akhuli |
Python3
# Python implementation of the above approach. import ctypes # Structure of a node in XOR linked list class Node: def __init__( self , value): self .value = value self .npx = 0 # create linked list class class XorLinkedList: # constructor def __init__( self ): self .head = None self .tail = None self .__nodes = [] # Function to insert a node with given value at given position def insert( self , value): # Initialize a new Node node = Node(value) # Check If XOR linked list is empty if self .head is None : # Update pointer of head node self .head = node # Update pointer of tail node self .tail = node else : # Update curr node address self .head.npx = id (node) ^ self .head.npx # Update new node address node.npx = id ( self .head) # Update head self .head = node # push node self .__nodes.append(node) # method to get length of linked list def Length( self ): if not self .isEmpty(): prev_id = 0 node = self .head next_id = 1 count = 1 while next_id: next_id = prev_id ^ node.npx if next_id: prev_id = id (node) node = self .__type_cast(next_id) count + = 1 else : return count else : return 0 def NthNode( self , N): count = 1 # Stores XOR pointer of # in previous Node prev_id = 0 prev1_id = 0 # Stores XOR pointer # in current node node = self .head node1 = self .head # Stores XOR pointer of # in next node next_id = 1 next1_id = 1 while (next_id and count < N): # Forward traversal next_id = prev_id ^ node.npx if next_id: # Update prev prev_id = id (node) # Update curr node = self .__type_cast(next_id) count = count + 1 # Move 1 step forward because in python, prev1_id and next1_id are # starting from 0 and 1 respectively, and not with None. next_id = prev_id ^ node.npx prev_id = id (node) node = self .__type_cast(next_id) if not next_id and count < N: print ( "Wrong Input" ) return while next_id: # Forward Traversal next_id = prev_id ^ node.npx next1_id = prev1_id ^ node1.npx # Update prev if next_id: prev_id = id (node) node = self .__type_cast(next_id) # Update curr if next_id: prev1_id = id (node1) node1 = self .__type_cast(next1_id) node1 = self .__type_cast(next1_id) print (node1.value) # Function to print elements of the XOR Linked List def printList( self ): if self .head ! = None : prev_id = 0 node = self .head next_id = 1 print (node.value, end = ' ' ) # Traverse XOR linked list while next_id: # Forward traversal next_id = prev_id ^ node.npx if next_id: # Update prev prev_id = id (node) # Update curr node = self .__type_cast(next_id) # Print current node print (node.value, end = ' ' ) else : return # method to check if the linked list is empty or not def isEmpty( self ): if self .head is None : return True return False # method to return a new instance of type def __type_cast( self , id ): return ctypes.cast( id , ctypes.py_object).value # Create following XOR Linked List # head -->7 β> 6 β>8 β> 11 β> 3 β> 1 β> 2 β> 0 head = XorLinkedList() head.insert( 0 ) head.insert( 2 ) head.insert( 1 ) head.insert( 3 ) head.insert( 11 ) head.insert( 8 ) head.insert( 6 ) head.insert( 7 ) head.NthNode( 3 ) # This code is contributed by Nidhi goel. |
Output
1
Time Complexity: O(N)
Auxiliary Space: O(1)