Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Friday, June 9, 2017

Even Odd In Linked List


Problem :
Segregate even and odd nodes in a Linked List
means make order (first even then odd in linked list without changing order of insertion)


Input:
8 120 18 5 4 1 63
Output :
8 120 18 4 5 1 63

Idea is to make two linkedlist and add even to one and odd to another.



import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
 {
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
   int n=ab.nextInt();
   LinkedList<Integer> lst1=new LinkedList<Integer>();
   LinkedList<Integer> lst2=new LinkedList<Integer>();
   for(int i=0;i<n;i++)
   {
       int temp=ab.nextInt();
       if(temp%2==0)
       lst1.add(temp);
       else
       lst2.add(temp);
   }
   Iterator<Integer> i1=lst1.iterator();
   while(i1.hasNext())
   System.out.print(i1.next()+" ");
   i1=lst2.iterator();
   while(i1.hasNext())
   System.out.print(i1.next()+" ");
   System.out.print("\n");
}
}
}

0 Comments:

Post a Comment

Stats