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

Powered by Blogger.

Wednesday, May 31, 2017

Java List Live Example


Problem: Here first n elemets will be given , insert them into list and then scan a variable k (no. of queries) 

Insert and Delete at given index


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class listexample{

    public static void main(String[] args) {
     
        List<Integer> list=new ArrayList<Integer>();
        Scanner ab=new Scanner(System.in);
        int n=ab.nextInt();
        int index;
        while(n-->0)
            {
            list.add(ab.nextInt());
        }
        n=ab.nextInt();
        while(n-->0)
            {
            String temp=ab.next();
            if(temp.equals("Insert"))
                {
                 index=ab.nextInt();
                int data=ab.nextInt();
                list.add(index,data);
            }
            else
                {
                 index=ab.nextInt();
                //++index;
                list.remove(index);
            }
        }
        for(int c:list)
            System.out.print(c+" ");
    }
}

0 Comments:

Post a Comment

Stats