Write a Java class myLinkedList to simulate a singly linked list using arrays as
ID: 3772305 • Letter: W
Question
Write a Java class myLinkedList to simulate a singly linked list using arrays as the underlying structure. Include the following methods:
1. insert an element within the linked list.(this should also work for the front and the rear of the list)
2. Remove an element from the linked list
3. display (print) the elements of the linked list in order.
4. An method to check if the list is "empty"
Test your solution using a linked list that initially has the characters A, B, D, E, F, and G. Insert "C" between B and D. Remove element "F".
[Hint: One solution is to use 2 arrays. One for the data, and the other for the "next" pointer. Also, consider using dummy nodes for the front, and possibly the rear of the list]
Explanation / Answer
CODE :
public class MyLinkedList {
public char[] myLinkListArray=new char[20];
public int head=0;
public int rear=0;
public void add(char num)
{
if(!isEmpty())
{
System.out.println("Link List if full!!");
}
else
{
myLinkListArray[rear]=num;
rear++;
}
}
public void remove(char num)
{
int temp=0;
if(rear==0)
{
System.out.println("List is Empty!");
}
else
{
for(int i=0;i<myLinkListArray.length;i++)
{
if(myLinkListArray[i]==num)
{
for(int j=i;j<19;j++)
{
myLinkListArray[j]=myLinkListArray[j+1];
}
rear--;
}
}
}
}
public void display()
{
for(int i=0;i<myLinkListArray.length;i++)
{
System.out.println(myLinkListArray[i]+" ");
}
}
public boolean isEmpty()
{
if(rear==19)
{
return false;
}
else
return true;
}
public static void main(String[] args)
{
MyLinkedList list=new MyLinkedList();
list.add('A');
list.add('B');
list.add('C');
list.display();
list.remove('A');
list.display();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.