【问题标题】:construct 2d array to emulate a linked list构造二维数组以模拟链表
【发布时间】:2017-11-19 22:41:45
【问题描述】:

我想在不使用 Java 链表对象的情况下创建一个双向链表。我想看看我是否可以使用二维数组来做到这一点:

  • 第一个维度是入口,
  • 第二个维度是前向指针、后向指针和节点的值。

这是我想要显示的内容,但不确定我是否正确

  1. 添加节点
  2. 从列表中间删除一个节点
  3. 在列表中间添加一个节点
  4. 交换链表的第一个和最后一个节点。

这是我的代码,非常感谢任何帮助。

public class TwoDArrayLinkedList {

static class Node {
    Node forwardPointer;
    Node backwardPointer;
    int data;
}

static void display(Node head) {
    Node RightPointer;
    Node LeftPointer = head;

    while (LeftPointer != null) {
        RightPointer = LeftPointer;

        while (RightPointer != null) {
            System.out.print(RightPointer.data + " ");
            RightPointer = RightPointer.forwardPointer;
        }
        System.out.println();
        System.out.println();
        System.out.println();
        LeftPointer = LeftPointer.backwardPointer;
    }
}

static Node construct(int array[][], int i, int j, int m, int n) {

    if (i > n - 1 || j > m - 1)
        return null;

    Node tempNode = new Node();
    tempNode.data = array[i][j];
    tempNode.forwardPointer = construct(array, i, j + 1, m, n);
    tempNode.backwardPointer = construct(array, i + 1, j, m, n);
    return tempNode;
    }


public static void main(String args[]) {
        int array[][] = { { 12, 22, 33 },
                    { 44, 54, 61 },
                   { 72, 82, 93 } };
    int m = 3, n = 3;
    Node head = construct(array, 0, 0, m, n);
    display(head);
    }
}

【问题讨论】:

  • 欢迎来到 SO。请使用tour to this site 并了解如何使用ask a question. 目前尚不清楚您对我们的要求。
  • 谢谢,yacc。我的问题是如何:1)添加一个节点 2)从列表中间删除一个节点 3)在列表中间添加一个节点 4)交换链表的第一个和最后一个节点。我觉得此时我的代码中没有完成 2、3 和 4。感谢您的帮助和热烈的欢迎!
  • 避免同时提出多个问题。项目列表太宽泛,无法得出准确的答案。您可能想在codereview.stackexchange.com 上询问意见或改进。

标签: java arrays linked-list 2d


【解决方案1】:

you are doing this ?

你没有让它成为双向链表你已经为链表矩阵编写了代码,这样每个节点都连接到它的下一个右节点和下节点。

要将 2D 数组作为双向链表,您需要遍历每个 2D Array 元素,并且需要为每个值创建一个新节点并分配前向和后向引用。 this might help you

【讨论】:

    猜你喜欢
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多