Make a class for a singly linked circular list that has no end and no beggining.
ID: 3533873 • Letter: M
Question
Make a class for a singly linked circular list that has no end and no beggining. The only access on the list is a single reference, current, that can point to any link on the list. This referance can move around the list as needed. The list should handle insertion, searching, deletion, display(although you'll need to break the circle at some arbitrary point to print it on the screen), and a step() method that moves current along to the next link.
Here is what I have so far. I beleieve my problem is only with my insert() method.
class Link
{
public int dData; // data item
public Link next; // next link in list
// -------------------------------------------------------------
public Link(int d) // constructor
{
dData = d;// initialize data
}
// -------------------------------------------------------------
public void displayLink() // display ourself
{
System.out.print("{" + dData + "} ");
}
} // end class Link
//---------------------------------------------------------------------------
class CircularLL
{
public Link head = null;
int nItems = 0;
public boolean isEmpty()
{
return (nItems == 0);
}
public int getSize()
{
return nItems;
}
// INSERT
public void insert(int key)
{
Link current = new Link(key);
if(isEmpty())
head = current;
current.next = head;
head = current;
nItems++;
}
// STEP
public void step()
{
if( head != null && head.next != null )
head = head.next;
}
// FIND
public Link find (int key)
{
Link current = head;
while(current.dData != key)
{
current = current.next;
}
return current;
}
// DELETE
public Link delete(int key)
{
Link current = head;
Link temp = head;
while(current.dData != key)
{
temp = current;
current = current.next;
}
if(current == head)
head = head.next;
else
{
temp.next = current.next;
nItems--;
}
return current;
}
// DISPLAY
public void displayList()
{
Link current = head; // start at beginning
int counter = nItems;
while(true)
{
if(counter != 0)
{
current.displayLink();
current = current.next; // move to next link
counter--;
}
else
break;
}
}
}
Explanation / Answer
public void insert(int key)
{
Link current = new Link(key);
if(isEmpty())
{
head = current;
current.next=null;
}
else
{
current.next = head;
head = current;
}
nItems++;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.