I am using a Linked list/ Iterater combo to compute the Josephus problem, and need it to only print if there is only one element left in the list, but how would I use an if statement to check a condition that references to the size of the list rather than the number in the list with "ourList" being of type "LinkedList"? Here is a piece of the code:
if(atEnd() == true){
//System.out.println("Value removed: " + current.dData);
previous.next = current.next;
current = ourList.getFirst();
//if(ourList == Only contains one element){ <--------------
//ourList.displayList();
// }
}
for reference heres my LinkedList + Iterator:
class Link{
public int dData;
public Link next;
public Link(int data){
dData = data;
}
public void displayLink(){
System.out.print(dData + " ");
}
}
class LinkList{
private Link first;
public LinkList(){
first = null;
}
public Link getFirst(){
return first;
}
public void setFirst(Link f){
first = f;
}
public boolean isEmpty(){
return first == null;
}
public ListIterator getIterator(){
return new ListIterator(this);
}
public void displayList(){
Link current = first;
while(current != null){
current.displayLink();
current = current.next;
}
System.out.println("");
}
}
class ListIterator{
private Link current;
private Link previous;
private LinkList ourList;
public ListIterator(LinkList list){
ourList = list;
reset();
}
public void reset(){
current = ourList.getFirst();
previous = null;
}
public boolean atEnd(){
return(current.next == null);
}
public boolean atEndPrevious(){
return(previous.next == null);
}
public Link getCurrent(){
return current;
}
public void nextLink(){
previous = current;
current = current.next;
}
public void insert(int value){
Link newLink = new Link(value);
if(ourList.isEmpty() == true){
ourList.setFirst(newLink);
current = newLink;
}else{
newLink.next = current.next;
current.next = newLink;
nextLink();
}
}
public void beginningPoint(int begin){
if(begin == 1){
current = ourList.getFirst();
previous = null;
// System.out.println("Current Location: " + current.dData);
}else if(begin != 1){
current = ourList.getFirst();
previous = null;
for(int i = 1; i < begin; i++){
nextLink();
// System.out.println("Current Location: " + current.dData);
}
}
}
Aucun commentaire:
Enregistrer un commentaire