• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

JAVA编写正确的构造函数

武飞扬头像
it1352
帮助123

前言

我正在为我的数据结构类处理一个项目,该项目要求我编写一个类来实现INT的链表。使用Node的内部类。

包括下面的方法。编写一个测试程序,使您能够以任何顺序使用您想要的任何数据来测试所有方法。

我必须创建三个不同的构造函数。

其中一个构造函数是一个构造函数,它接受一个整型数组,并创建一个包含所有整型的链表。

我试着做了下面的代码。

但我不确定我写的代码是否正确?

是否有人可以验证我是否正确编写了代码,或者是否可以让我知道需要更改哪些内容才能正确编写代码?

import java.util.Random;

public class LinkedListOfIntsTest {
    Node head;
    int[] array;
    Node other;

    private class Node {
        int value;
        Node nextNode;

        public Node(int value, Node nextNode) {
            this.value = value;
            this.nextNode = nextNode;
        }

    }

    public LinkedListOfIntsTest() {
        
    }

    public LinkedListOfIntsTest(int[] other) {
        array = new int[other.length];
        
    }

 解答

整个想法是将数组转换为LinkedList,而不仅仅是存储数组。因此,您应该从类的字段中删除Node otherint[] array

执行转换的一种方法是将数组的每个元素转换为Node,在执行过程中链接到前一个元素,如下所示。

public LinkedListOfIntsTest(int[] other) {
    Node[] nodes = new Node[other.length];
    for( int index = 0; index < other.length; index   ) {
        nodes[index] = new Node(other[index], null);
        if (index > 0) {
            nodes[index - 1].nextNode = nodes[index];
        }
    }
    
    head = nodes[0];
}

这里,nodes只是一个局部变量,因为在构造函数完成后您不再需要它。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanegga
系列文章
更多 icon
同类精品
更多 icon
继续加载