Open In App

Rearrange Linked List to make XOR of nodes at same distance from start and end same

Last Updated : 30 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a linked list containing N nodes of binary numbers, the task is to check whether it is possible to rearrange the linked list in such a way that value of XOR between element at ith Node and N+1−ith node is the same for all 1 ≤ i ≤ N. Print Yes, if the Linked List can be rearranged, or else print No.

Examples:

Input: LL = 0 -> 0 -> 1
Output: Yes
Explanation : 001 can be rearranged to form 010 which means 0 ⊕  0 = 0 and 1 ⊕ 1 =0 are same . So output is 1.

Input : 0001 (0->0->0->1)
Output : No
Explanation : 0001  can not be rearranged . So output is 0.

 

Approach: The idea is based on the linked list traversal, based on following observations: 

Case 1: If size of linked linked list is odd, then it is always possible. So directly return Yes
For example:

  • 00001 can be rearranged as 00100
  • 00011 can be rearranged as 10001
  • 00111 can be rearranged as 10101
  • 01111 can be rearranged as 11011

Case 2: If size of linked linked list is even, Count the number of 1 present in linked list. If number of 1s present in linked list is equal to the half the size of linked list, then return Yes, because rearrangement will be always possible.
For example: 

  • 0011  
    number of 1’s = half of size of linked list 
    so it can be rearranged as 1001
  • 001101  
    number of 1’s = half of size of linked list 
    so it can be rearranged as 010101

Case 3: if number of 1’s present in our linked list is even, then also it is always possible. So directly return Yes.
For example: 

  • 000011 can be rearranged as 100001 or 001100
  • 011 can be rearranged as 101

Case 4: if above all conditions are false, then return No.
For example: 

  • 011111 cannot be rearranged
  • 000001 cannot be rearranged

Follow the below steps to implement the above approach:

  • Calculate the size of linked list.
  • If size is odd then return 1 because it is always possible to rearrange linked list as discuss above.
  • If size is even, count the number of node consist value 1.
  • If count of number of node consist value 1 is half of  the size of linked list then return 1.
  • If size is even and count of number of node consist value 1 is even then return 1.
  • If all the above condition is fail to execute then return 0.

Below is the implementation of the above approach:

C++




// C++ code for the above approach:
#include <iostream>
using namespace std;
 
// Node Class
class Node {
public:
    int data;
    Node* next;
};
 
// Function to append the node
void append(Node** head_ref, int new_data)
{
    Node* new_node = new Node();
    Node* last = *head_ref;
    new_node->data = new_data;
    new_node->next = NULL;
    if (*head_ref == NULL) {
        *head_ref = new_node;
        return;
    }
    while (last->next != NULL) {
        last = last->next;
    }
    last->next = new_node;
    return;
}
 
// Count the size of linked list
int CountSize(Node* head)
{
    Node* temp = head;
    int count = 0;
    while (temp != NULL) {
        count++;
        temp = temp->next;
    }
    return count;
}
 
// Bool function to check
// is it possible to make
// such linked list
bool isPossible(Node* head)
{
 
    // count size of linked list
    int n = CountSize(head);
 
    // if n is odd
    if (n % 2 != 0) {
        return 1;
    }
 
    else {
        int o = 0;
        Node* temp = head;
 
        while (temp != NULL) {
            if (temp->data == 1) {
                o++;
            }
            temp = temp->next;
        }
 
        if (o == (n / 2)) {
            return 1;
        }
        else if (o % 2 == 0) {
            return 1;
        }
        else {
            return 0;
        }
    }
}
 
// Driver Code
int main()
{
    Node* head = NULL;
    append(&head, 0);
    append(&head, 0);
    append(&head, 1);
    append(&head, 1);
 
    cout << (isPossible(head) == 1
                 ? "Yes"
                 : "No")
         << endl;
}


Java




// Java code to implement the approach
import java.io.*;
import java.util.*;
 
class GFG {
  // Structure of a binary tree node
  public static class Node {
    int data;
    Node next;
 
    Node(int data)
    {
      this.data = data;
      this.next = null;
 
    }
  }
 
  // Count the size of linked list
  static int CountSize(Node head) {
    Node temp = head;
    int count = 0;
    while (temp != null) {
      count++;
      temp = temp.next;
    }
    return count;
  }
 
  // Bool function to check
  // is it possible to make
  // such linked list
  static int isPossible(Node head) {
 
    // count size of linked list
    int n = CountSize(head);
 
    // if n is odd
    if (n % 2 != 0) {
      return 1;
    }
 
    else {
      int o = 0;
      Node temp = head;
 
      while (temp != null) {
        if (temp.data == 1) {
          o++;
        }
        temp = temp.next;
      }
 
      if (o == Math.floor(n / 2)) {
        return 1;
      }
      else if (o % 2 == 0) {
        return 1;
      }
      else {
        return 0;
      }
    }
  }
 
 
  // Driver Code
  public static void main(String[] args)
  {
    Node head = new Node(1);
    head.next = new Node(1);
    head.next.next = new Node(0);
    head.next.next.next = new Node(0);
    System.out.println((isPossible(head) == 1
                        ? "Yes"
                        : "No"));
  }
}
 
// This code is contributed by jana_sayantan.


Python3




# Python code for the above approach
 
# Node Class
class Node:
    def __init__(self,d):
            self.data = d
            self.next = None
             
# Count the size of linked list
def CountSize(head):
    temp = head
    count = 0
    while (temp != None):
        count += 1
        temp = temp.next
     
    return count
 
# Bool function to check
# is it possible to make
# such linked list
def isPossible(head):
 
    # count size of linked list
    n = CountSize(head)
 
    # if n is odd
    if (n % 2 != 0):
        return 1
 
    else:
        o = 0
        temp = head
 
        while (temp != None):
            if (temp.data == 1):
                o += 1
             
            temp = temp.next
         
 
        if (o == (n // 2)):
            return 1
         
        elif (o % 2 == 0):
            return 1
 
        else:
            return 0
 
# Driver Code
head = Node(1)
head.next = Node(1)
head.next.next = Node(0)
head.next.next.next = Node(0)
print("Yes" if(isPossible(head) == 1) else "No")
 
# This code is contributed by shinjanpatra


C#




// C# program to implement above approach
using System;
 
public class Node {
     public int data;
     public Node next;
     public Node(int d)
     {
        data = d;
        next = null;
     } // Constructor
}
 
public class LinkedList{
  public Node head;
   
      // Count the size of linked list
  public int CountSize()
  {
      Node temp = head;
      int count = 0;
      while (temp != null) {
          count++;
          temp = temp.next;
      }
      return count;
  }
   
  public Node append(Node node,int val)
  {
    Node new_node = new Node(val);
    node.next = new_node;
    return new_node;
  }
}
 
public class GFG
{
  public static bool isPossible(LinkedList LL)
  {
 
      // count size of linked list
      int n = LL.CountSize();
 
      // if n is odd
      if (n % 2 != 0) {
          return true;
      }
      else
      {
          int o = 0;
          Node temp = LL.head;
 
          while (temp != null) {
              if (temp.data == 1) {
                  o++;
              }
              temp = temp.next;
          }
 
          if (o == (n / 2)) {
              return true;
          }
          else if (o % 2 == 0) {
              return true;
          }
          else {
              return false;
          }
      }
  }
   
  // Driver Code
  public static void Main()
  {
    LinkedList llist = new LinkedList();
   
    llist.head = new Node(0);
    Node cur = llist.head;
    cur = llist.append(cur, 0);
    cur = llist.append(cur, 1);
    cur = llist.append(cur, 1);
     
    if(isPossible(llist))
    {
        Console.Write("Yes\n");
    }
    else
    {
          Console.Write("No\n");
    }
  }
}
 
// This code is contributed by subhamgoyal2014.


Javascript




<script>
        // JavaScript code for the above approach
 
        // Node Class
        class Node {
            constructor(d) {
                this.data = d;
                this.next = null;
            }
        };
 
        // Count the size of linked list
        function CountSize(head) {
            let temp = head;
            let count = 0;
            while (temp != null) {
                count++;
                temp = temp.next;
            }
            return count;
        }
 
        // Bool function to check
        // is it possible to make
        // such linked list
        function isPossible(head) {
 
            // count size of linked list
            let n = CountSize(head);
 
            // if n is odd
            if (n % 2 != 0) {
                return 1;
            }
 
            else {
                let o = 0;
                let temp = head;
 
                while (temp != null) {
                    if (temp.data == 1) {
                        o++;
                    }
                    temp = temp.next;
                }
 
                if (o == Math.floor(n / 2)) {
                    return 1;
                }
                else if (o % 2 == 0) {
                    return 1;
                }
                else {
                    return 0;
                }
            }
        }
 
        // Driver Code
        let head = new Node(1);
        head.next = new Node(1);
        head.next.next = new Node(0)
        head.next.next.next = new Node(0)
        document.write((isPossible(head) == 1
            ? "Yes"
            : "No")
            + '<br>')
 
     // This code is contributed by Potta Lokesh
    </script>


 
 

Output

Yes

 

Time Complexity : O(N)
Auxiliary Space : O(1)

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads