In: Computer Science
I need to create a linked list that contains a fixed arraylist. Each new entry is added to array list. If the arraylist is full, create a new arraylist and add to the linklist. In java please.
Note:
here the arraylist size is considered as 3. You can set any limit you wanted. Following code may be difficult to understand but after seeing it 7 to 8 times and reading comments ,you can understand it easily
Code
import java.util.*;
public class LinkedList
{
Node head;
static class Node
{
int a=0;
public int get()
{
return a;
}
public void set()
{
a=a+1;
}
public void reset()
{
a=0;
}
ArrayList <Integer> al = new ArrayList<Integer>(3);
Node next;
Node(int d)
{
al.add(d);
next=null;
}
void add(int d)
{
al.add(d);
}
}
public static LinkedList insert(LinkedList list,int data)
{
if(list.head==null) //if head is null create head
{
Node node= new Node(data);
node.set(); //arraylist size is 1
node.next=null;
list.head=node;
}
else
{
Node last=list.head;
while(last.next!=null)
{
last=last.next; //reach the last node
}
if(last.get()==3) //if areaylist size reached the limit create new node
{
Node node=new Node(data);
node.reset(); //set reset get all of them uses to check limit of list size
node.set();
node.next=null;
last.next=node;
}
else//if arraylist limit not reached add elements in the same node
{
last.add(data);
last.set(); //increase arraylist size after insert elements in linkedlist
}
}
return list;
}
public static void print(LinkedList list)
{
Node cur=list.head;
while(cur!=null)
{
System.out.print(cur.al+" ");
cur=cur.next;
}
}
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l = insert(l, 1);
l = insert(l, 2);
l = insert(l, 3);
l = insert(l, 4);
l = insert(l, 5);
l = insert(l, 6);
l = insert(l, 6);
l = insert(l, 7);
l = insert(l, 8);
print(l);
}
}
Terminal Work
.