我正在為我的資料結構類開發一個專案,該專案要求我撰寫一個類來實作一個整數鏈表。
- 為節點使用內部類。
- 包括以下方法。
- 撰寫一個測驗器,使您能夠以任何順序使用您想要的任何資料測驗所有方法。
我必須創建一個名為“public int[] toArray()”的方法。此方法旨在“回傳包含串列中所有整數的整數陣列”。我在下面有這個方法的代碼。但是,當我嘗試將陣列轉換為串列時,我的代碼不起作用。當我運行代碼時,我得到一個填充了 head 值的陣列。例如,如果我有一個串列 [9, 15, 3, 16, 5, 1, 17, 6, 2, 9]。我的輸出是 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]。我試過查找它,但代碼與我的專案設定方式不匹配。有人知道如何將鏈表轉換為陣列嗎?
import java.util.Random;
import java.util.Scanner;
public class LinkedListOfInts {
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
}
public LinkedListOfInts(LinkedListOfInts other) {
Node tail = null;
for (Node n = other.head; n != null; n = n.nextNode) {
if (tail == null)
this.head = tail = new Node(n.value, null);
else {
tail.nextNode = new Node(n.value, null);
tail = tail.nextNode;
}
}
}
public LinkedListOfInts(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];
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i )
this.addToFront(random.nextInt(high - low) low);
}
public void addToFront(int x) {
head = new Node(x, head);
}
public int[] toArray() {
int i = 0;
int[] array = new int[getLength()];
for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
array[i ] = head.value;
}
return array;
}
public String toString() {
String result = " ";
for (Node ptr = head; ptr != null; ptr = ptr.nextNode)
result = ptr.value " ";
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
LinkedListOfInts copy = new LinkedListOfInts(list);
boolean done = false;
while (!done) {
System.out.println("1. Reverse");
System.out.println("2. toString");
switch (input.nextInt()) {
case 11:
System.out.println("Array");
System.out.println(list.toArray());
break;
case 12:
System.out.println("toString");
System.out.println(list.toString());
break;
}
}
}
}
uj5u.com熱心網友回復:
思路是從頭到尾遍歷鏈表,然后存盤所有元素。事實上,您已經在使用 toString() 方法做到這一點。
由于您不知道鏈表中元素的數量,因此您需要動態增加陣列的大小。在 java 中,我個人只建議使用串列。
因此,該方法將遵循以下原則:
public Integer[] toArray() {
ArrayList<Integer> list = new ArrayList();
for(Node node = head; head != null; head = head.nextNode) {
list.add(node.value);
}
return (Integer[]) list.toArray();
}
請注意,我目前正在直接訪問 node.value,考慮到它實際上是類代碼庫的一部分,這有點好。然而,更好的選擇是使用 getter(并使每個內部值私有)。然而,我不確定他們是否已經考慮過封裝的概念,但它在 Java 中非常重要。
uj5u.com熱心網友回復:
public int[] toArray() {
int i = 0;
int[] array = new int[getLength()];
for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
array[i ] = ptr.value;
}
return array;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321525.html
