2015-06-05 6 views
1

Я создаю LinkedList с нуля, в виде поезда. Поэтому у меня есть класс Domino, который создает каждый узел, а затем у меня есть класс Train, который включает в себя методы add, size, remove и т. Д. Моя проблема:removeZero() метод при создании связанного списка?

  • removeZeros() method: У меня не может быть никаких параметров, но я должен удалить все узлы с нулями в них. Вместо этого моя программа находит все нули в списке и удаляет все узлы до тех пор, пока не будет больше нулей. Нули были добавлены в класс клиента.

вот мой поезд класс:

public class Train{ 

private Domino engine; 
private Domino caboose; 
private int insertS; 


public Train(){ 
    engine = null; 
    caboose = engine; 
} 
/** WHERE IM HAVING TROUBLE 
* removeZero() - remove any Dominos from the train that have one or more zero spots 
* while maintaining the linked list structure. 
*/ 

// method is now just getting the spot1 0 and printing that 
public void removeZero(){ 
    Domino current = engine; 
    Domino hold = caboose.next; 

     while (current != hold) { 

     if(current.spot1 == 0 ||current.spot2 == 0){ 

       current = current.next; 
       engine = current; 
       System.out.println("b " + engine); 

      }else{ 

       current = current.next; 


      } 
      } 
public String toString(){ 
    String ts = "{ empty }"; 
    if (engine == null) { 
     return ts; 
    } else { 
     Domino hold = engine; 
     ts = "{ "; 
      while (hold != caboose) { 
       ts += hold + ", "; 
       hold = hold.next; 
      } 
     ts += hold + " }"; 
    } 
    return ts; 

} 
/** 
* 
* add(spot1, spot2) - add a Domino to the end of the Train with the given spots 
*/ 
public void add(int spot1, int spot2){ 
    if (engine == null) { 
     engine = new Domino(spot1,spot2); 
     caboose = engine; 

    } else { 
     caboose.next = new Domino(spot1, spot2, null,caboose); 
     //tail.next.back = tail; 
     caboose = caboose.next; 
    } 

} 



} 

/** 
* reversePrint() - like toString, but provides a String that lists 
* all of the Dominos that are in the Train in reverse order 
*/ 
public String reversePrint() { 
    Domino hold = caboose; 
    String reverse = "{ empty }"; 

    if (engine == null) { 
     System.out.println(reverse); 
    } else { 
     reverse = "{ "; 
      while (hold != engine){ 
       reverse += hold + ", "; 
       hold = hold.back; 
      } 
     reverse += hold + " }"; 
    } 
    return reverse; 
} 
/** 
* size() - return the number of Dominos in the Train 
*/ 
public int size(){ 
    int count = 0; 
    Domino hold = engine; 
    while(hold != null){ 
     hold = hold.next; 
     count++; 
    } 
    return count; 
} 
/** insert(spot1, spot2, next, back) - insert a Domino in the middle of 
* the Train where spot2 is the same as the spot1 of the next Domino and spot1 
* is the same as spot2 of the previous Domino. 
* (private) 
*/ 
private void insert(int spot1,int spot2){ 
    if (!(insertS == search)) { 
     Domino hold = engine; 
     while (hold != caboose) { 
      if (hold.spot1 == search) { 
       Domino newDom = new Domino(spot1, spot2, null,caboose);  
       hold.next = newDom;    
       newDom.next.back = newDom; 
       hold = hold.next;    

      } else { 
       hold = hold.next;    
      } 
     }  
     if (hold.spot2 == search) { 
      add(spot1, spot2);        
     } 
    } else { 
     System.out.println(" ** Error Inserting these values will cause an infinite loop:"); 
     System.out.println(" * * * " + insertS + " and " + search + " * * *"); 
    } 

} 

/** 
* build() - scans through the Train creating links, using insert(spot1, spot2), between 
* existing Dominos where the second spot of the first Domino does not match the 
* first spot of the second domino, no param 
*/ 

public void build(){ 
    insert(search, insertS); 
} 

}

вот мой Domino класс:

public class Domino{ 
    public int spot1; // the leading half how many spots it has 
    public int spot2; // the trailing half how many spots it has 
    public Domino next; // a link to the next Domino (type)? 
    public Domino back; // a link to the previous Domino 
private int zero; 


/** 
    * Constructor 
    * Creates null Domino 
    * 
    */ 
    public Domino(){ 
    this(0,0 , null, null); 
} 
/** 
    * Constructor 
    * a constructor for Domino with given spots 
    */ 
    public Domino(int spot1, int spot2){ 
    this(spot1,spot2, null, null); 
} 
/** 
    * Constructor 
    * @param: all fields 
    * setting variables 
    */ 
    public Domino(int spot1, int spot2, Domino next, Domino back){ 
    this.spot1 = spot1; 
    this.spot2 = spot2; 
    this.next = next; 
    this.back = back; 
} 
/** 
    * toString(): prints out single Domino 
    * 
    */ 
    public String toString(){ 
     if(this == null){ 
     return("[empty]"); 
    }else{ 
     return("[ " + spot1 + " | "+ spot2 + "]"); 
    } 

    } 



} 

Я действительно застрял на этом за прошедший день или так и не может показаться, чтобы понять это. Любая помощь будет большой. Если вам нужен код клиента, скажите об этом. Благодаря!

ответ

0

В случае столкновения с нулевым домино, вы назначаете двигатель текущим домино. Поскольку движок является заголовком списка, это эквивалентно удалению всех элементов, предшествующих тому, который содержит нуль. Удаление в связанном списке, как правило, осуществляется что-то вроде:

toDelete.back.next = toDelete.next; 
toDelete.next.back = toDelete.back 

где toDelete является Domino объект с нуля в данном случае. Поскольку ни одно домино теперь не имеет ссылки на домино toDelete, оно по существу удаляется.