多维四向链表

时间:2013-01-18 01:57:28

标签: java reference linked-list

好吧..所以我决定尝试使用Java中的链表而不是通常用来引用指针的C ++。

遍历可以是中心节点的上,下,左,右。对于角落中的节点,它们只移动两个方向,边缘上的节点可以移动3个方向。所有其他方向可以移动4个。

问题:

当我的程序离开构造函数时,我的节点以某种方式被删除:S当我使用get / set时,它不能遍历链接,因为它们是null。除了第一个节点。

我的节点是:

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);
    }
}

所以当我尝试将值设置在矩阵的中间附近时,它会抛出一个空指针错误。如果我尝试在构造函数中设置它,它工作得很好..因此我的节点必须以某种方式获取垃圾清洗..

1 个答案:

答案 0 :(得分:3)

在迭代列时,遍历行的次数。即,在您的示例中,访问的实际节点是(9,3),超出了Matrix的范围。

相反,您应该在整行中迭代一次,然后在列中向下迭代一次。

for (int K = 0; K < J; ++K) {
    Iterator = Iterator.Down;
}

for (int L = 0; L < I; ++L) {
    Iterator = Iterator.Right;
}

您是不是只使用二维数组?