Java Program to Implement Unrolled Linked List
Last Updated :
11 Apr, 2023
An Unrolled Linked List is a special type of Linked List in which each node stores an array of elements, unlike a simple linked list. Here we use an ArrayList and a constructor that initializes the size of the Unrolled Linked List. Elements are added to the first Node until it is filled and then a new Node is created with the same size.
The Node class has two methods namely
- A constructor
- An insert method which takes an integer as a parameter.
Implementation:
- Adding elements to the unrolled linked list
- Deleting elements from an unrolled linked list
Example 1: Adding elements to Unrolled Linked List
Java
import java.io.*;
import java.util.*;
class GFG {
static class Node {
int size;
ArrayList<Integer> array;
Node next = null ;
Node( int size)
{
this .size = size;
array = new ArrayList<>();
}
void insert( int n)
{
if (array.size() < size) {
array.add(n);
}
else {
if (next == null ) {
next = new Node(size);
next.insert(n);
}
else {
next.insert(n);
}
}
}
}
public static void main(String args[])
{
Node x = new Node( 3 );
x.insert( 10 );
x.insert( 20 );
x.insert( 30 );
x.insert( 40 );
x.insert( 50 );
x.insert( 60 );
x.insert( 70 );
while (x != null ) {
System.out.println(x.array);
x = x.next;
}
}
}
|
Output
[10, 20, 30]
[40, 50, 60]
[70]
Example 2: Deleting elements from an unrolled linked list
Java
import java.io.*;
import java.util.*;
class GFG {
static class Node {
int size;
ArrayList<Integer> array;
Node next = null ;
Node( int size)
{
this .size = size;
array = new ArrayList<>();
}
void insert( int n)
{
if (array.size() < size) {
array.add(n);
}
else {
if (next == null ) {
next = new Node(size);
next.insert(n);
}
else {
next.insert(n);
}
}
}
boolean delete( int n)
{
if (array.contains(n)) {
array.remove(array.indexOf(n));
return true ;
}
else {
if (next == null ) {
return false ;
}
else {
next.delete(n);
}
return true ;
}
}
}
public static void main(String args[])
{
Node x = new Node( 3 );
x.insert( 10 );
x.insert( 20 );
x.insert( 30 );
x.insert( 40 );
x.insert( 50 );
x.insert( 60 );
x.insert( 70 );
System.out.println(
"After Inserting all elements : " );
Node temp = x;
while (temp != null ) {
System.out.println(temp.array);
temp = temp.next;
}
System.out.println( "Deleting 50 :" );
x.delete( 50 );
temp = x;
while (temp != null ) {
System.out.println(temp.array);
temp = temp.next;
}
}
}
|
Output
After Inserting all elements :
[10, 20, 30]
[40, 50, 60]
[70]
Deleting 50 :
[10, 20, 30]
[40, 60]
[70]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...