好的..所以我决定尝试使用 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;
}
}
我执行如下操作:
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;
}
}
主要的喜欢:
package linkedlist;
public class LinkedList {
public static void main(String[] args) {
Matrix M = new Matrix(6, 6);
M.SetValue(3, 3, 10);
}
}
因此,当我尝试将值设置在矩阵中间附近时,它会引发空指针错误。如果我尝试在构造函数中设置它,它工作得很好。因此,我的节点必须以某种方式得到垃圾清理。