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
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
How to create a pointer to another pointer in a linked list?
Next article icon

Point to next higher value node in a linked list with an arbitrary pointer

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a singly linked list with every node having an additional arbitrary pointer that currently points to NULL. The task is to make the arbitrary pointer point to the next higher-value node.

listwithArbit

A Simple Solution is to traverse all nodes one by one, for every node, find the node that has the next greater value of the current node and change the next pointer. Time Complexity of this solution is O(n^2).

Using Merge Sort – O(nlogn) Time and O(n) Space

The approach involves using a modified Merge Sort for linked list while maintaining the original sequence and linking each node to the next higher value using an auxiliary arbit pointer. Initially, the arbit pointer of each node is set to point to the next node. The list is recursively split into smaller sections, which are then sorted and merged back together. During merging, the arbit pointers are updated to point to the next higher value node. This method efficiently sorts the list and adjusts the arbit pointers to maintain the desired order without altering the original list structure.

C++
// C++ implementation to point to next higher value // with an arbitrary pointer using merge sort approach #include <iostream> using namespace std;  class Node { public:     int data;     Node* next;        // Pointer to next higher node     Node* arbit;       Node(int x) {         data = x;         next = nullptr;         arbit = nullptr;     } };  // Function to merge two sorted lists Node* SortedMerge(Node* left, Node* right) {        // If one list is empty, return the other     if (!left) return right;     if (!right) return left;      Node* result = nullptr;     Node* curr = nullptr;      // Initialize result with the smaller node     if (left->data <= right->data) {         result = left;         left = left->arbit;     } else {         result = right;         right = right->arbit;     }     curr = result;      // Merge the two lists     while (left && right) {         if (left->data <= right->data) {             curr->arbit = left;             left = left->arbit;         } else {             curr->arbit = right;             right = right->arbit;         }         curr = curr->arbit;     }      // Attach remaining nodes     curr->arbit = left ? left : right;     return result; }  // Function to split the list into two halves Node* split(Node* head) {        // If list is empty or has one node     if (!head || !head->arbit) return nullptr;      Node* slow = head;     Node* fast = head->arbit;      // Move slow and fast pointers to find middle     while (fast && fast->arbit) {         slow = slow->arbit;         fast = fast->arbit->arbit;     }      // Split the list into two halves     Node* second = slow->arbit;     slow->arbit = nullptr;     return second; }  // Recursive merge sort for arbit pointers Node* MergeSort(Node* head) {        // If list is empty or has one node     if (!head || !head->arbit) return head;      // Split the list into two halves     Node* left = head;     Node* right = split(head);      // Recursively sort both halves     left = MergeSort(left);     right = MergeSort(right);      // Merge the two sorted halves     return SortedMerge(left, right); }  // Function to populate arbit pointers Node* populateArbit(Node* head) {     Node* curr = head;      // Initialize arbit pointers to next nodes     while (curr) {         curr->arbit = curr->next;         curr = curr->next;     }      // Sort the list using arbit pointers     return MergeSort(head); }  void printListArbit(Node* node) {     Node* curr = node;      while (curr) {         cout << curr->data << " ";         curr = curr->arbit;     }     cout << endl; }  int main() {        // Create a hardcoded linked list     // List: 5 -> 10 -> 2 -> 3     Node* head = new Node(5);     head->next = new Node(10);     head->next->next = new Node(2);     head->next->next->next = new Node(3);      // Populate arbit pointers to next higher node     head = populateArbit(head);      printListArbit(head);      return 0; } 
Java
// Java implementation to point to next higher value // with an arbitrary pointer using merge sort approach class Node {     int data;     Node next;        // Pointer to next higher node     Node arbit;       Node(int x) {         data = x;         next = null;         arbit = null;     } }  class GfG {        // Function to merge two sorted lists     public static Node SortedMerge(Node left, Node right) {            // If one list is empty, return the other         if (left == null) return right;         if (right == null) return left;          Node result = null;         Node curr = null;          // Initialize result with the smaller node         if (left.data <= right.data) {             result = left;             left = left.arbit;         } else {             result = right;             right = right.arbit;         }         curr = result;          // Merge the two lists         while (left != null && right != null) {             if (left.data <= right.data) {                 curr.arbit = left;                 left = left.arbit;             } else {                 curr.arbit = right;                 right = right.arbit;             }             curr = curr.arbit;         }          // Attach remaining nodes         curr.arbit = (left != null) ? left : right;         return result;     }      // Function to split the list into two halves     public static Node split(Node head) {            // If list is empty or has one node         if (head == null || head.arbit == null) return null;          Node slow = head;         Node fast = head.arbit;          // Move slow and fast pointers to find middle         while (fast != null && fast.arbit != null) {             slow = slow.arbit;             fast = fast.arbit.arbit;         }          // Split the list into two halves         Node second = slow.arbit;         slow.arbit = null;         return second;     }      // Recursive merge sort for arbit pointers     public static Node MergeSort(Node head) {            // If list is empty or has one node         if (head == null || head.arbit == null) return head;          // Split the list into two halves         Node left = head;         Node right = split(head);          // Recursively sort both halves         left = MergeSort(left);         right = MergeSort(right);          // Merge the two sorted halves         return SortedMerge(left, right);     }      // Function to populate arbit pointers     public static Node populateArbit(Node head) {         Node curr = head;          // Initialize arbit pointers to next nodes         while (curr != null) {             curr.arbit = curr.next;             curr = curr.next;         }          // Sort the list using arbit pointers         return MergeSort(head);     }      public static void printListArbit(Node node) {         Node curr = node;          while (curr != null) {             System.out.print(curr.data + " ");             curr = curr.arbit;         }         System.out.println();     }      public static void main(String[] args) {            // Create a hardcoded linked list         // List: 5 -> 10 -> 2 -> 3         Node head = new Node(5);         head.next = new Node(10);         head.next.next = new Node(2);         head.next.next.next = new Node(3);          // Populate arbit pointers to next higher node         head = populateArbit(head);          printListArbit(head);     } } 
Python
# Python program to point to next higher value # with an arbitrary pointer using merge sort approach class Node:     def __init__(self, x):         self.data = x         self.next = None         self.arbit = None   # Function to merge two sorted lists def SortedMerge(left, right):        # If one list is empty, return the other     if not left:         return right     if not right:         return left      result = None     curr = None      # Initialize result with the smaller node     if left.data <= right.data:         result = left         left = left.arbit     else:         result = right         right = right.arbit     curr = result      # Merge the two lists     while left and right:         if left.data <= right.data:             curr.arbit = left             left = left.arbit         else:             curr.arbit = right             right = right.arbit         curr = curr.arbit      # Attach remaining nodes     curr.arbit = left if left else right     return result   # Function to split the list into two halves def split(head):        # If list is empty or has one node     if not head or not head.arbit:         return None      slow = head     fast = head.arbit      # Move slow and fast pointers to find middle     while fast and fast.arbit:         slow = slow.arbit         fast = fast.arbit.arbit      # Split the list into two halves     second = slow.arbit     slow.arbit = None     return second   # Recursive merge sort for arbit pointers def MergeSort(head):        # If list is empty or has one node     if not head or not head.arbit:         return head      # Split the list into two halves     left = head     right = split(head)      # Recursively sort both halves     left = MergeSort(left)     right = MergeSort(right)      # Merge the two sorted halves     return SortedMerge(left, right)   # Function to populate arbit pointers def populateArbit(head):     curr = head      # Initialize arbit pointers to next nodes     while curr:         curr.arbit = curr.next         curr = curr.next      # Sort the list using arbit pointers     return MergeSort(head)   def printListArbit(node):     curr = node      while curr:         print(curr.data, end=" ")         curr = curr.arbit     print()   if __name__ == "__main__":        # Create a hardcoded linked list     # List: 5 -> 10 -> 2 -> 3     head = Node(5)     head.next = Node(10)     head.next.next = Node(2)     head.next.next.next = Node(3)      # Populate arbit pointers to next higher node     head = populateArbit(head)      printListArbit(head) 
C#
// C# program to point to next higher value // with an arbitrary pointer using merge sort approach using System;  class Node {     public int data;     public Node next;        // Pointer to next higher node     public Node arbit;       public Node(int x) {         data = x;         next = null;         arbit = null;     } }  class GfG {        // Function to merge two sorted lists     public static Node SortedMerge(Node left, Node right) {            // If one list is empty, return the other         if (left == null) return right;         if (right == null) return left;          Node result = null;         Node curr = null;          // Initialize result with the smaller node         if (left.data <= right.data) {             result = left;             left = left.arbit;         } else {             result = right;             right = right.arbit;         }         curr = result;          // Merge the two lists         while (left != null && right != null) {             if (left.data <= right.data) {                 curr.arbit = left;                 left = left.arbit;             } else {                 curr.arbit = right;                 right = right.arbit;             }             curr = curr.arbit;         }          // Attach remaining nodes         curr.arbit = (left != null) ? left : right;         return result;     }      // Function to split the list into two halves     public static Node Split(Node head) {            // If list is empty or has one node         if (head == null || head.arbit == null) return null;          Node slow = head;         Node fast = head.arbit;          // Move slow and fast pointers to find middle         while (fast != null && fast.arbit != null) {             slow = slow.arbit;             fast = fast.arbit.arbit;         }          // Split the list into two halves         Node second = slow.arbit;         slow.arbit = null;         return second;     }      // Recursive merge sort for arbit pointers     public static Node MergeSort(Node head) {            // If list is empty or has one node         if (head == null || head.arbit == null) return head;          // Split the list into two halves         Node left = head;         Node right = Split(head);          // Recursively sort both halves         left = MergeSort(left);         right = MergeSort(right);          // Merge the two sorted halves         return SortedMerge(left, right);     }      // Function to populate arbit pointers     public static Node PopulateArbit(Node head) {         Node curr = head;          // Initialize arbit pointers to next nodes         while (curr != null) {             curr.arbit = curr.next;             curr = curr.next;         }          // Sort the list using arbit pointers         return MergeSort(head);     }      public static void PrintListArbit(Node node) {         Node curr = node;          while (curr != null) {             Console.Write(curr.data + " ");             curr = curr.arbit;         }         Console.WriteLine();     }      public static void Main() {            // Create a hardcoded linked list         // List: 5 -> 10 -> 2 -> 3         Node head = new Node(5);         head.next = new Node(10);         head.next.next = new Node(2);         head.next.next.next = new Node(3);          // Populate arbit pointers to next higher node         head = PopulateArbit(head);          PrintListArbit(head);     } } 
JavaScript
// JavaScript implementation to point to next higher value // with an arbitrary pointer using merge sort approach class Node {     constructor(x) {         this.data = x;         this.next = null;         this.arbit = null;     } }  // Function to merge two sorted lists function SortedMerge(left, right) {        // If one list is empty, return the other     if (!left) return right;     if (!right) return left;      let result = null;     let curr = null;      // Initialize result with the smaller node     if (left.data <= right.data) {         result = left;         left = left.arbit;     } else {         result = right;         right = right.arbit;     }     curr = result;      // Merge the two lists     while (left && right) {         if (left.data <= right.data) {             curr.arbit = left;             left = left.arbit;         } else {             curr.arbit = right;             right = right.arbit;         }         curr = curr.arbit;     }      // Attach remaining nodes     curr.arbit = left ? left : right;     return result; }  // Function to split the list into two halves function split(head) {        // If list is empty or has one node     if (!head || !head.arbit) return null;      let slow = head;     let fast = head.arbit;      // Move slow and fast pointers to find middle     while (fast && fast.arbit) {         slow = slow.arbit;         fast = fast.arbit.arbit;     }      // Split the list into two halves     let second = slow.arbit;     slow.arbit = null;     return second; }  // Recursive merge sort for arbit pointers function MergeSort(head) {        // If list is empty or has one node     if (!head || !head.arbit) return head;      // Split the list into two halves     let left = head;     let right = split(head);      // Recursively sort both halves     left = MergeSort(left);     right = MergeSort(right);      // Merge the two sorted halves     return SortedMerge(left, right); }  // Function to populate arbit pointers function populateArbit(head) {     let curr = head;      // Initialize arbit pointers to next nodes     while (curr) {         curr.arbit = curr.next;         curr = curr.next;     }      // Sort the list using arbit pointers     return MergeSort(head); }  function printListArbit(node) {     let curr = node;      while (curr) {         process.stdout.write(curr.data + " ");         curr = curr.arbit;     }     console.log(); }  // Create a hardcoded linked list // 5 -> 10 -> 2 -> 3 let head = new Node(5); head.next = new Node(10); head.next.next = new Node(2); head.next.next.next = new Node(3);  // Populate arbit pointers to next higher node head = populateArbit(head);  printListArbit(head); 

Output
2 3 5 10 

Time Complexity: O(nlogn), as we are using the Merge Sort technique
Auxiliary Space: O(n) , where n is number of elements in linked list.



Next Article
How to create a pointer to another pointer in a linked list?

S

Saurabh Bansal
Improve
Article Tags :
  • DSA
  • Linked List
Practice Tags :
  • Linked List

Similar Reads

  • Javascript Program For Pointing To Next Higher Value Node In A Linked List With An Arbitrary Pointer
    Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher-value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all n
    4 min read
  • Point arbit pointer to greatest value right side node in a linked list
    Given singly linked list with every node having an additional “arbitrary” pointer that currently points to NULL. We need to make the “arbitrary” pointer to the greatest value node in a linked list on its right side. A Simple Solution is to traverse all nodes one by one. For every node, find the node
    15+ min read
  • Delete a Node in a Singly Linked List with Only a Pointer
    Given only a pointer to a node to be deleted in a singly linked list. The task is to delete that node from the list. Note: The given pointer does not point to the last node of the linked list. Examples: Input: LinkedList: 1->2->3->4->5, delete_ptr = 2Output: LinkedList: 1->3->4-
    6 min read
  • Clone a linked list with next and random pointer in O(1) space
    Given a linked list of size N where each node has two links: next pointer pointing to the next node and random pointer to any random node in the list. The task is to create a clone of this linked list in O(1) space, i.e., without any extra space.  Examples:  Input: Head of the below linked list Outp
    10 min read
  • How to create a pointer to another pointer in a linked list?
    In this article we cover how to create a pointer to another pointer in a linked list, it can be singly, doubly, or circularly. What is Linked List: A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked
    7 min read
  • Sum of nodes in a linked list which are greater than next node
    Given a linked list, the task is to find the sum of all the nodes which are greater than the node next to them. Note that for the last node of the linked list which doesn't have any node next to it, it must be greater than the first node in order for it to contribute to the sum.Examples: Input: 9 -
    7 min read
  • Sorted insert in a doubly linked list with head and tail pointers
    A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list rema
    10 min read
  • Delete linked list nodes which have a greater value on left side
    Given a singly linked list, the task is to remove all the nodes which have a greater value on the left side. Examples: Input: 12->15->10->11->5->6->2->3Output: Modified Linked List = 12 15 Input: 25->15->6->48->12->5->16->14Output: Modified Linked List = 14
    7 min read
  • Write a function to get Nth node in a Linked List
    Given a LinkedList and an index (1-based). The task is to find the data value stored in the node at that kth position. If no such node exists whose index is k then return -1. Example:  Input: 1->10->30->14, index = 2Output: 10Explanation: The node value at index 2 is 10 Input: 1->32->
    11 min read
  • Partitioning a linked list around a given value and keeping the original order
    Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than x. The original relative order of the nodes in each of the three partitions should be preserved. Examples: Input : 1 -> 4
    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