本文介紹了我是否正確地編寫了這個(gè)構(gòu)造函數(shù)?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我正在為我的數(shù)據(jù)結(jié)構(gòu)類處理一個(gè)項(xiàng)目,該項(xiàng)目要求我編寫一個(gè)類來(lái)實(shí)現(xiàn)INT的鏈表。使用Node的內(nèi)部類。包括下面的方法。編寫一個(gè)測(cè)試程序,使您能夠以任何順序使用您想要的任何數(shù)據(jù)來(lái)測(cè)試所有方法。我必須創(chuàng)建三個(gè)不同的構(gòu)造函數(shù)。其中一個(gè)構(gòu)造函數(shù)是一個(gè)構(gòu)造函數(shù),它接受一個(gè)整型數(shù)組,并創(chuàng)建一個(gè)包含所有整型的鏈表。我試著做了下面的代碼。但我不確定我寫的代碼是否正確?是否有人可以驗(yàn)證我是否正確編寫了代碼,或者是否可以讓我知道需要更改哪些內(nèi)容才能正確編寫代碼?
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];
}
推薦答案
否,整個(gè)想法是將數(shù)組轉(zhuǎn)換為LinkedList
,而不僅僅是存儲(chǔ)數(shù)組。因此,您應(yīng)該從類的字段中刪除Node other
和int[] array
。
執(zhí)行轉(zhuǎn)換的一種方法是將數(shù)組的每個(gè)元素轉(zhuǎn)換為Node
,在執(zhí)行過(guò)程中鏈接到前一個(gè)元素,如下所示。
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
只是一個(gè)局部變量,因?yàn)樵跇?gòu)造函數(shù)完成后您不再需要它。
這篇關(guān)于我是否正確地編寫了這個(gè)構(gòu)造函數(shù)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,