Given a Linked List of even number of nodes, the task is to generate a new Linked List such that it contains the maximum difference of squares of node values in decreasing order by including each node in a single pair.
Examples:
Input: 1 -> 6 -> 4 -> 3 -> 5 ->2
Output: 35 -> 21 -> 7
Explanation:
The difference between squares of 6 and 1 forms the first node with value 35.
The difference between squares of 5 and 2 forms the second node with value 21.
The difference between squares of 4 and 3 forms the third node with value 7.
Therefore, the formed LL is 35 -> 21 -> 7.Input: 2 -> 4 -> 5 -> 3 -> 7 -> 8 -> 9 -> 10
Output: 96 -> 72 -> 48 -> 24
Explanation:
The difference between squares of 10 and 2 forms the first node with value 96.
The difference between squares of 9 and 3 forms the second node with value 72.
The difference between squares of 8 and 4 forms the third node with value 48.
The difference between squares of 7 and 5 forms the fourth node with value 24.
Therefore, the formed LL is 96 -> 72 -> 48 -> 24.
Approach: The approach is to find the maximum value of a node and always make the difference between the largest and the smallest node value. So create a deque and insert all node’s value in it, and sort the deque. Now, access the largest and smallest values from both ends. Below are the steps:
- Create a deque and insert all values into the deque.
- Sort the deque to get the largest node value and smallest node value in constant time.
- Create another linked list having the value difference of square’s of the largest and the smallest values from the back and the front of the deque respectively.
- After each iteration, pop both the smallest and largest value from the deque.
- After the above steps, print the nodes of the new Linked List formed.
Below is the implementation of the above approach:
C++
// C++ program for the above approach Â
#include <bits/stdc++.h> using namespace std; Â
// Linked list node struct Node { Â Â Â Â int data; Â Â Â Â struct Node* next; }; Â
// Function to push into Linked List void push( struct Node** head_ref,           int new_data) {     // Allocate node     struct Node* new_node         = ( struct Node*) malloc (             sizeof ( struct Node)); Â
    // Put in the data     new_node->data = new_data;     new_node->next = (*head_ref); Â
    // Move the head to point     // to the new node     (*head_ref) = new_node; } Â
// Function to print the Linked List void print( struct Node* head) { Â Â Â Â Node* curr = head; Â
    // Iterate until curr is NULL     while (curr) { Â
        // Print the data         cout << curr->data << " " ; Â
        // Move to next         curr = curr->next;     } } Â
// Function to create a new Node of // the Linked List struct Node* newNode( int x) {     struct Node* temp         = ( struct Node*) malloc (             sizeof ( struct Node)); Â
    temp->data = x;     temp->next = NULL; Â
    // Return the node created     return temp; } Â
// Function used to re-order list struct Node* reorder(Node* head) { Â Â Â Â // Stores the node of LL Â Â Â Â deque< int > v; Â Â Â Â Node* curr = head; Â
    // Traverse the LL     while (curr) {         v.push_back(curr->data);         curr = curr->next;     } Â
    // Sort the deque     sort(v.begin(), v.end()); Â
    // Node head1 stores the     // head of the new Linked List     Node* head1 = NULL;     Node* prev = NULL; Â
    // Size of new LL     int x = v.size() / 2; Â
    // Loop to make new LL     while (x--) {         int a = v.front();         int b = v.back(); Â
        // Difference of squares of         // largest and smallest value         int ans = pow (b, 2) - pow (a, 2); Â
        // Create node with value ans         struct Node* temp = newNode(ans);         if (head1 == NULL) {             head1 = temp;             prev = temp;         } Â
        // Otherwise, update prev         else {             prev->next = temp;             prev = temp;         } Â
        // Pop the front and back node         v.pop_back();         v.pop_front();     } Â
    // Return head of the new LL     return head1; } Â
// Driver Code int main() { Â Â Â Â struct Node* head = NULL; Â
    // Given Linked list     push(&head, 6);     push(&head, 5);     push(&head, 4);     push(&head, 3);     push(&head, 2);     push(&head, 1); Â
    // Function Call     Node* temp = reorder(head); Â
    // Print the new LL formed     print(temp); Â
    return 0; } |
Java
// Java program for the // above approach import java.util.*; class GFG{ Â
// Linked list node static class Node { Â Â int data; Â Â Node next; }; Â
static Node head ; Â
// Function to push // into Linked List static void push( int new_data) {   // Allocate node   Node new_node = new Node(); Â
  // Put in the data   new_node.data = new_data;   new_node.next = head; Â
  // Move the head to point   // to the new node   head = new_node; } Â
// Function to print the // Linked List static void print(Node head) { Â Â Node curr = head; Â
  // Iterate until curr   // is null   while (curr != null )   {     // Print the data     System.out.print(curr.data + " " ); Â
    // Move to next     curr = curr.next;   } } Â
// Function to create a // new Node of the Linked List static Node newNode( int x) { Â Â Node temp = new Node(); Â Â temp.data = x; Â Â temp.next = null ; Â
  // Return the node   // created   return temp; } Â
// Function used to re-order // list static Node reorder(Node head) { Â Â // Stores the node of LL Â Â Deque<Integer> v = Â Â Â Â Â Â Â Â new LinkedList<>(); Â Â Node curr = head; Â
  // Traverse the LL   while (curr != null )   {     v.add(curr.data);     curr = curr.next;   } Â
  // Sort the deque   // Collections.sort(v); Â
  // Node head1 stores the   // head of the new Linked   // List   Node head1 = null ;   Node prev = null ; Â
  // Size of new LL   int x = v.size() / 2 ; Â
  // Loop to make new LL   while ((x--) > 0 )   {     int a = v.peek();     int b = v.getLast(); Â
    // Difference of squares of     // largest and smallest value     int ans = ( int )(Math.pow(b, 2 ) -                     Math.pow(a, 2 )); Â
    // Create node with value ans     Node temp = newNode(ans);     if (head1 == null )     {       head1 = temp;       prev = temp;     } Â
    // Otherwise, update prev     else     {       prev.next = temp;       prev = temp;     } Â
    // Pop the front and     // back node     v.removeFirst();     v.removeLast();   } Â
  // Return head of the   // new LL   return head1; } Â
// Driver Code public static void main(String[] args) { Â Â head = null ; Â
  // Given Linked list   push( 6 );   push( 5 );   push( 4 );   push( 3 );   push( 2 );   push( 1 ); Â
  // Function Call   Node temp = reorder(head); Â
  // Print the new   // LL formed   print(temp); } } Â
// This code is contributed by Amit Katiyar |
Python3
# Python3 program for the # above approach from collections import deque Â
# Linked list node class Node:        def __init__( self , x):                self .data = x         self . next = None Â
# Function to push into Linked List # Function to push into Linked List def push(head_ref, new_data): Â
    new_node = Node(new_data)     new_node. next = head_ref     head_ref = new_node     return head_ref Â
# Function to print the Linked List def printt(head): Â
    curr = head Â
    # Iterate until curr     # is None     while (curr): Â
        # Print the data         print (curr.data,               end = " " ) Â
        # Move to next         curr = curr. next Â
# Function used to re-order list # Function used to re-order list def reorder(head): Â Â Â Â Â Â Â # Stores the node of LL Â Â Â Â arr = [] Â Â Â Â curr = head Â
    while curr:         arr.append(curr.data)         curr = curr. next Â
    arr = sorted (arr) Â
    # Sort the deque     v = deque() Â
    for i in arr:         v.append(i) Â
    # Node head1 stores the     # head of the new Linked List     head1 = None     prev = None Â
    x = len (arr) / / 2 Â
    while x:         a = v.popleft()         b = v.pop() Â
        # Difference of squares of         # largest and smallest value         ans = pow (b, 2 ) - pow (a, 2 ) Â
        temp = Node(ans) Â
        if head1 = = None :             head1 = temp             prev = temp         else :             prev. next = temp             prev = temp         x - = 1 Â
    # Return head of the new LL     return head1 Â
# Driver Code if __name__ = = '__main__' : Â Â Â Â Â Â Â head = None Â
    # Given Linked list     head = push(head, 6 )     head = push(head, 5 )     head = push(head, 4 )     head = push(head, 3 )     head = push(head, 2 )     head = push(head, 1 ) Â
    # Function Call     temp = reorder(head) Â
    # Print the new LL formed     printt(temp) Â
# This code is contributed by Mohit kumar 29 |
C#
// C# program for the // above approach using System; using System.Collections.Generic; class GFG{ Â
// Linked list node public class Node { Â Â public int data; Â Â public Node next; }; Â
static Node head ; Â
// Function to push // into Linked List static void push( int new_data) {   // Allocate node   Node new_node = new Node(); Â
  // Put in the data   new_node.data = new_data;   new_node.next = head; Â
  // Move the head to point   // to the new node   head = new_node; } Â
// Function to print the // Linked List static void print(Node head) { Â Â Node curr = head; Â
  // Iterate until curr   // is null   while (curr != null )   {     // Print the data     Console.Write(curr.data + " " ); Â
    // Move to next     curr = curr.next;   } } Â
// Function to create a // new Node of the Linked List static Node newNode( int x) { Â Â Node temp = new Node(); Â Â temp.data = x; Â Â temp.next = null ; Â
  // Return the node   // created   return temp; } Â
// Function used to re-order // list static Node reorder(Node head) { Â Â // Stores the node of LL Â Â List< int > v = Â Â Â Â Â Â Â new List< int >();Â Â Â Â Â Â Node curr = head; Â
  // Traverse the LL   while (curr != null )   {     v.Add(curr.data);     curr = curr.next;   } Â
  // Sort the deque   // Collections.sort(v); Â
  // Node head1 stores the   // head of the new Linked   // List   Node head1 = null ;   Node prev = null ; Â
  // Size of new LL   int x = v.Count / 2; Â
  // Loop to make new LL   while ((x--) > 0)   {     int a = v[0];     int b = v[v.Count-1]; Â
    // Difference of squares of     // largest and smallest value     int ans = ( int )(Math.Pow(b, 2) -                     Math.Pow(a, 2)); Â
    // Create node with value ans     Node temp = newNode(ans);     if (head1 == null )     {       head1 = temp;       prev = temp;     } Â
    // Otherwise, update prev     else     {       prev.next = temp;       prev = temp;     } Â
    // Pop the front and     // back node     v.RemoveAt(0);     v.RemoveAt(v.Count - 1);   } Â
  // Return head of the   // new LL   return head1; } Â
// Driver Code public static void Main(String[] args) { Â Â head = null ; Â
  // Given Linked list   push(6);   push(5);   push(4);   push(3);   push(2);   push(1); Â
  // Function Call   Node temp = reorder(head); Â
  // Print the new   // LL formed   print(temp); } } Â
// This code is contributed by gauravrajput1 |
Javascript
<script> // javascript program for the // above approach Â
    // Linked list node     class Node {         constructor(val) {             this .data = val;             this .next = null ;         }     } Â
    var head; Â
    // Function to push     // into Linked List     function push(new_data) {         // Allocate node         var new_node = new Node(); Â
        // Put in the data         new_node.data = new_data;         new_node.next = head; Â
        // Move the head to point         // to the new node         head = new_node;     } Â
    // Function to print the     // Linked List     function print(head) {         var curr = head; Â
        // Iterate until curr         // is null         while (curr != null ) {             // Print the data             document.write(curr.data + " " ); Â
            // Move to next             curr = curr.next;         }     } Â
    // Function to create a     // new Node of the Linked List     function newNode(x) {         var temp = new Node();         temp.data = x;         temp.next = null ; Â
        // Return the node         // created         return temp;     } Â
    // Function used to re-order     // list     function reorder(head) {         // Stores the node of LL         var v = [];         var curr = head; Â
        // Traverse the LL         while (curr != null ) {             v.push(curr.data);             curr = curr.next;         } Â
        // Sort the deque         // Collections.sort(v); Â
        // Node head1 stores the         // head of the new Linked         // List         var head1 = null ;         var prev = null ; Â
        // Size of new LL         var x = v.length / 2; Â
        // Loop to make new LL         while ((x--) > 0) {             var a = v[0];             var b = v[v.length-1]; Â
            // Difference of squares of             // largest and smallest value             var ans = parseInt( (Math.pow(b, 2) - Math.pow(a, 2))); Â
            // Create node with value ans             var temp = newNode(ans);             if (head1 == null ) {                 head1 = temp;                 prev = temp;             } Â
            // Otherwise, update prev             else {                 prev.next = temp;                 prev = temp;             } Â
            // Pop the front and             // back node             v.pop();             v.shift();         } Â
        // Return head of the         // new LL         return head1;     } Â
    // Driver Code              head = null ; Â
        // Given Linked list         push(6);         push(5);         push(4);         push(3);         push(2);         push(1); Â
        // Function Call         var temp = reorder(head); Â
        // Print the new         // LL formed         print(temp); Â
// This code is contributed by todaysgaurav </script> |
35 21 7
Â
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!