COMPARE TWO LINKED LISTS

COMPARE TWO LINKED LISTS

Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, print 1. Otherwise, print 0.

Example

list 1= 1->2->3->NULL

list 2= 1->2->3->4->NULL

Input

The first line contains two integers m and n, the number of nodes in the first linked list and second linked list respectively.

Second line contains m spaced integers, each a value for a data attribute.

Third line contains m spaced integers, each a value for a data attribute.

Output

Compare the two linked lists and print 1 if the lists are equal. Otherwise, print 0.

Constraints

1<=n,m<=1000

1<=llist1[i],llist2[i]<=1000

Sample Input

2 1
1 2
1

Sample Output

0

Explanation

Linked list 1= 1->2->NULL

Linked list 2= 1->NULL

It is clearly visible that the two linked lists are not equal. Therefore, print 0.

Solution of COMPARE TWO LINKED LISTS:–

import java.util.*;
import java.lang.*;
import java.io.*;

class Node{
  int data;
  Node next;

  Node(int x)
  {
    data=x;
    next=null;
  }
}

public class Main
{
  
  static Node head=null;
  static boolean flag=false;
  static void insertionM(int x)
  {
    Node newNode = new Node(x);
     if(head==null)
     {
       head=newNode;
       return;
     }

    Node temp=head;
    while(temp.next!=null)
      {
        temp=temp.next;
      }
    temp.next=newNode;
  }

  static Node headOne=null;
  static void insertionN(int x)
  {
    Node newNode = new Node(x);
     if(headOne==null)
     {
       headOne=newNode;
       return;
     }

    Node temp=headOne;
    while(temp.next!=null)
      {
        temp=temp.next;
      }
    temp.next=newNode;
  }

  static void printList()
  {
     Node temp=head;
    while(temp!=null)
      {
        System.out.print(temp.data+" ");
        temp=temp.next;
      }
  }

  static boolean compare()
  {
      Node temp=head;
      Node demo=headOne;

    while(temp!=null && demo!=null)
      {
         if(temp.data == demo.data)
         {
            flag=true;
         }
        else{
            flag=false;
            break;
        }
        temp=temp.next;
        demo=demo.next;
      }
    return flag;
  }

  

  
  
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      int m = sc.nextInt();
      int n = sc.nextInt();

      for(int i=0;i<m;i++)
        {
          int value=sc.nextInt();
          insertionM(value);
        }

      for(int i=0;i<n;i++)
        {
          int value=sc.nextInt();
          insertionN(value);
        }

      if(m!=n)
      {
         System.out.print(0);
         return;
      }
     boolean flag= compare();
      if(flag==true)
      {
        System.out.print(1);
      }
      else{
        System.out.print(0);
      }
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *