I have to create a method to eliminate numbers in a circular linked list
say we have values up to 9
1 2 3 4 5 6 7 8 9
and we want to continually remove every 4th integer going through, it would go as followed
5 6 7 8 9 1 2 3; // 4 is removed
9 1 2 3 5 6 7; // 8 is removed
5 6 7 9 1 2; // 3 is removed
1 2 5 6 7; // 9 is removed
7 1 2 5; // 6 is removed
7 1 2; // 5 is removed
1 2; // 7 is removed
1; // 2 is removed
I have to create a move to traverse through the elements, and an eliminate to remove the element, but I can do that on my own. I am having a problem with my toString(); method, I am currently not returning any value.
class Digit{
class DigitNode
{
public int num=0; // Digit's position in line
public DigitNode next=null; // Reference to next digit
/**
* Digit constructor, initializes number
*/
public DigitNode(int number)
{
//
num = number;
next = null;
}
}
private int number;
private DightNode current = null; // Linked list of digits
private DigitNode tail = null; // Tracks end of list as it is constructed
/**
* constructs a circular linked list of
* @param n DigitNodes, current is the first DigitNode and tail is the last DigitNode(next of tail is current)
*/
public Digit(int n)
{
//
number = n;
current = null;
tail = null;
}
/*
* prints all Digits starting from current until tail
*/
@Override
public String toString()
{
//
String strVal = "";
DigitNode position = current;
while (position != null) {
strVal = strVal + position + " ";
position = current.next;
}
return strVal;
}
To me, I understand that I'm assigning position as the current value which should be 1
, thus while position is not null
, strVal
be the position [1]
+ " "
for spacing. then I call position to be the next value which is [2]
, and I continue until null
which is after 9
. Thus strVal
should be 1 2 3 4 5 6 7 8 9
. But I'm not return anything unfortunately, I tried debugging, and placing some System.out.prinln();
markers to see if I was returning anything, but I wasnt.
First of all, you need to fill your Digit
with DigitNode
's objects. I don't see the code which does that from snapshot you posted.
Presumably you could do this in constructor of Digit
, or create a method Digit
.add(DigitNode
node). You need this, otherwise your current
will always be null.
Next, you need to add toString in DigitNode
as I said earlier in the comment, or you could change Digit
.toString() to have :
strVal = strVal + position.num + " "; // note position.num to get the number