2015-05-10 4 views
0

Я хочу создать n элементов в двусвязном списке в Java. Я пытаюсь построить матрицу с ссылками справа, слева, вверх и вниз, чтобы построить игру pentomino, которая является точной проблемой покрытия, чтобы решить ее. Поэтому мне нужно реализовать Алгоритм X от Кнута.Использование цикла for для создания дважды связанного списка java

Как создать n-элементы в двусвязном списке с помощью цикла for? Я не хочу потерять свой h-узел, потому что это запись в мой двойной список.

Мой код:

public class PentominoWLIDLX 
{ 
    static Node h;     // header element 

    public PentominoWLIDLX(int n) 
    { 
    h = new Node(); 
    // create n columns 
    Node temp = h; 
    for (int i = 1; i <= n; i++) 
    { 
     Node newColumn = new Node(i); 

     temp.R = newColumn.L; 

     temp.L = newColumn.R; 

     temp = newColumn; 
    } 
    } 


class Node // represents 1 element or header 
{ 
    Node C; // reference to column-header << h?, 
    Node L; // left 
    Node R; // right 
    Node U; // reference up 
    Node D; // down reference down 

    int position; 

    Node() 
    { 
     C = L = R = U = D = this; 
    } 

    Node(int i) 
    { 
     C = L = R = U = D = this; // double-linked circular list 
     this.position = i; 
    } 

    public int getPosition() 
    { 
     return this.position; 
    } 
} // end of class 

public static void main(String[] args) 
{ 
    PentominoWLIDLX p = new PentominoWLIDLX(3); 
    System.out.println("h. " + h.getPosition()); 
    System.out.println("h.getClass: " + h.getClass()); 
    System.out.println("h.1R: " + h.R.getPosition()); 
    System.out.println("h.2R: " + h.R.R.getPosition()); 
    System.out.println("h.3R: " + h.R.R.R.getPosition()); 
    System.out.println("h.4R: " + h.R.R.R.R.getPosition()); 
    System.out.println("h.1L: " + h.L.getPosition()); 
    System.out.println("h.2L: " + h.L.L.getPosition()); 
    System.out.println("h.3L: " + h.L.L.L.getPosition()); 
    System.out.println("h.4L: " + h.L.L.L.L.getPosition()); 
    System.out.println("h.U " + h.U.getPosition()); 
} 
}//end of class 

ответ

0

Решено:

public PentominoWLIDLX(int n) 
{ 
    h = new Node(); 
    columnList = new ArrayList<PentominoWLIDLX.Node>(); 
    rowList = new ArrayList<PentominoWLIDLX.Node>(); 
    // create n columns 
    columnList.add(h); 

    for (int i = 1; i <= n; i++) 
    { 
     Node column = new Node(i); // create new column 
     columnList.add(column);  // add it to list 
    } 

    columnList.get(0).L = columnList.get(columnList.size()-1); 
    columnList.get(columnList.size()-1).R = columnList.get(0); 
    for (int i = 0; i < columnList.size(); i++) 
    { 
     if (i > 0) 
     columnList.get(i).L = columnList.get(i-1); 

     if (i < (columnList.size()-1)) 
     columnList.get(i).R = columnList.get(i+1); 
    } 
} 
Смежные вопросы