0

所以我的问题开始于是否有可能在 Java 中创建一个链表数组?

关于我为什么要问的一些背景。我正在做一个项目,在这个项目中我们得到了一个方阵文件。我们必须找到矩阵的行列式,但它们必须存储在链接结构中。我们以前使用数组做过同样的事情,所以我可以从那个数组中重用我的源代码。这是我要做的事情(主要基于我以前的项目):

  1. 将文件的每一行作为字符串读取
  2. 计算矩阵的数量并确定每个矩阵的开始和结束位置。
  3. * 将每个矩阵的每个元素读入一个多链接的 ListNode(我将为那些编写类)
  4. * 对每个矩阵重复
  5. 处理每个的行列式。

所以这两个加星标的步骤是我很难弄清楚的。我想一次读取所有矩阵,这样我就不会忘记我在文件中的位置,就像我在一个矩阵中读取一样,做了行列式,然后返回文件获取另一个。但是,我不知道如何存储每个链表表示,以便我可以迭代地处理每个。我唯一的想法是将每个矩阵读入链表结构,并尽可能将每个链表结构存储在一个数组中。如果不可能,有什么可能的替代方案?

4

3 回答 3

1

存储一个 LinkedLists 数组是完全可能的;数组可以应用于对象以及原始类型。但是,我建议创建一个 Matrix 类,因为方阵不是链表;他们有二维的数据,而不仅仅是一个。至少,您可以使用一个二维浮点数组来表示一个矩阵,并存储一个双 [][] 的 LinkedList。您的表示越接近实际对象,对您来说就越容易。

于 2012-07-29T20:45:53.307 回答
0

如果您被允许使用 java 已有的标准 LinkedList 类,这里是读取和存储矩阵的可能实现:

int size = 10; //width and height of your matrix. 

LinkedList<LinkedList<Integer>> matrix = new LinkedList<LinkedList<Integer>>();

for (int i = 0; i<size; i++)
{
    LinkedList<Integer> list = new LinkedList<Integer>();
    for (int j = 0; j < size; j++)
    {
        //read the actual item
    }
    matrix.add(list);
}

对于读取矩阵(可能是数字),我建议使用名为 Scanner 的类。您可以创建一个新的扫描仪,将能够读取您的文件,编号:

Scanner sc = new Scanner(new File("input.txt"));

您可以使用它读取整数值,而无需像这样进行任何转换:

int x = sc.nextInt();
于 2012-07-29T21:13:28.457 回答
0

You can make an array of linked lists in Java by declaring LinkedList[], but if you do, your performance will suffer badly. A look at matrix multiplication will illustrate the reason.

If A and B are matrices where the A's column count equals B's row count, then A * B[r, c] is the dot product of row r in A with column c in B. This means we have to extract rows and columns from our matrices.

If we form matrices from lists (of any sort), we can store them row-wise (i.e., where the 0-th list represents row 0), or column-wise (where the 0-th list represents column 0).

Now we run into a problem. In a linked list, the method get(n) starts at the beginning of the list and finds the next member n times -- which makes it run in order n time. A matrix built from linked lists will either extract columns very slowly (if stored row-wise), or extract rows very slowly (if stored column-wise).

I's suggest keeping it simple by using arrays of arrays. You can allocate an n x n array with

int[][] values = new int[n][n];

The value 'n' must be defined, of course.

Hope that this helps.

于 2012-07-29T22:08:11.800 回答