Bra*_*don 5 java reference linked-list
好的..所以我决定尝试在 Java 中使用链表而不是通常的 C++,我习惯于在 ..
对于中心节点,遍历可以是向上、向下、向左、向右。对于角上的节点,它们只能移动两个方向,边缘上的节点可以移动 3 个方向。所有其他节点都可以移动 4 个方向。
问题:
当我的程序离开构造函数时,我的节点以某种方式被删除 :S 当我使用 get/set 时,它无法遍历链接,因为它们为空......除了第一个节点。
我的节点是:
package linkedlist;
public class Node {
public Node Up, Down, Left, Right;
public int Value;
public Node() {
Value = -1;
Up = Down = Left = Right = null;
}
}
Run Code Online (Sandbox Code Playgroud)
我执行如下:
package linkedlist;
public class Matrix {
private int Width, Height;
private Node Reference;
public Matrix(int Width, int Height) {
Reference = new Node();
this.Width = Width; this.Height = Height;
Node RowIterator = Reference, ColumnIterator = Reference;
for (int I = 0; I < Height; ++I) {
for (int J = 0; J < Width; ++J) {
if (I == 0) {
if (J < Width - 1) {
RowIterator.Right = new Node();
RowIterator.Right.Left = RowIterator;
RowIterator = RowIterator.Right;
}
}
else {
if (I < Height - 1) {
ColumnIterator.Down = new Node();
}
RowIterator = ColumnIterator;
RowIterator.Right = new Node();
RowIterator.Up = ColumnIterator;
RowIterator.Up.Down = RowIterator;
RowIterator.Right.Left = RowIterator;
RowIterator.Right.Up = RowIterator.Up.Right;
RowIterator = RowIterator.Right;
ColumnIterator = ColumnIterator.Down;
}
}
}
}
public void SetValue(int I, int J, int Value) {
//Same as get except it sets rather than returns..
}
public int GetValue(int I, int J) {
RowIterator = ColumnIterator = Reference;
for (int K = 0; K < J; ++K) {
for (int L = 0; L < I; ++L) {
RowIterator = RowIterator.Right;
}
ColumnIterator = ColumnIterator.Down;
RowIterator = ColumnIterator;
}
return RowIterator.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
主要喜欢:
package linkedlist;
public class LinkedList {
public static void main(String[] args) {
Matrix M = new Matrix(6, 6);
M.SetValue(3, 3, 10);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我尝试在矩阵中间附近设置值时,它会引发空指针错误。
沿行迭代的次数与沿列迭代的次数相同。即,在您的示例中,访问的实际节点是 (9, 3),超出了Matrix.
相反,您应该在行中迭代一次,然后在列中迭代一次。
for (int K = 0; K < J; ++K) {
Iterator = Iterator.Down;
}
for (int L = 0; L < I; ++L) {
Iterator = Iterator.Right;
}
Run Code Online (Sandbox Code Playgroud)
您不只使用二维数组有什么特殊原因吗?