首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在java中实现二维链表?

在Java中实现二维链表可以通过自定义数据结构来实现。下面是一个简单的示例代码:

代码语言:txt
复制
public class Node {
    int data;
    Node right;
    Node down;

    public Node(int data) {
        this.data = data;
        this.right = null;
        this.down = null;
    }
}

public class TwoDLinkedList {
    Node head;

    public void insertRow(int[] rowData) {
        Node newRow = null;
        Node temp = null;

        for (int i = 0; i < rowData.length; i++) {
            Node newNode = new Node(rowData[i]);

            if (newRow == null) {
                newRow = newNode;
            } else {
                temp.right = newNode;
            }

            temp = newNode;
        }

        if (head == null) {
            head = newRow;
        } else {
            Node lastRow = head;
            while (lastRow.down != null) {
                lastRow = lastRow.down;
            }
            lastRow.down = newRow;
        }
    }

    public void display() {
        Node row = head;
        while (row != null) {
            Node node = row;
            while (node != null) {
                System.out.print(node.data + " ");
                node = node.right;
            }
            System.out.println();
            row = row.down;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        TwoDLinkedList list = new TwoDLinkedList();
        list.insertRow(new int[]{1, 2, 3});
        list.insertRow(new int[]{4, 5, 6});
        list.insertRow(new int[]{7, 8, 9});

        list.display();
    }
}

这个示例中,我们定义了一个Node类作为二维链表的节点,其中包含一个整数数据data、一个指向右边节点的指针right和一个指向下方节点的指针down。然后,我们定义了一个TwoDLinkedList类作为二维链表的主类,其中包含一个头节点head。通过insertRow方法可以插入一行数据,通过display方法可以打印出整个二维链表。

这个示例只是一个简单的实现,实际应用中可能需要根据具体需求进行扩展和优化。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券