我如何像老师所说的那样“将您的链表复制到无序数组中”?我不知道是否应该使用迭代器,但迭代器不是仅将链表复制到另一个链表吗?任何帮助欢迎。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
import jsjf.*;
public class Hw10
{
public static void main(String[] args) throws FileNotFoundException
{
//-------------------------------------------------
//Stack
//-------------------------------------------------
ArrayListStack <Names> transactions = new ArrayListStack<>();
//-------------------------------------------------
//Linked List
//-------------------------------------------------
LinkedUnorderedList<Names> list = new LinkedUnorderedList<>();
//-------------------------------------------------
// File Scanner
//-------------------------------------------------
Scanner fileScan = new Scanner(new File("input.txt"));
//-------------------------------------------------
//Variables that the scanner will read in
//-------------------------------------------------
int code;
String name;
int age;
Names obj;
//-------------------------------------------------
//While Loop to read in file adding to the stack and linked list
//-------------------------------------------------
while(fileScan.hasNext())
{
code = fileScan.nextInt();
if(code == 3)
{
name = fileScan.next();
age = fileScan.nextInt();
obj = new Names(name,age);
transactions.push(obj);
}
else if (code == 1)
{
name = fileScan.next();
age =fileScan.nextInt();
obj = new Names(name,age);
list.addToFront(obj);
}
}
/*
System.out.print(list.toString());
System.out.print("-------------");
System.out.print(transactions.toString());
*/
//-------------------------------------------------
//iterator / copy / queue-- copy linked list into unordered array
//-------------------------------------------------
ArrayListQueue <Names> aq = new ArrayListQueue();
}
最佳答案
您可以在一行代码中完成此操作。
假设您有一个这样的列表:
List<Names> transactions;
要将其转换为数组,只需执行以下操作:
Names[] transactionsArray = transactions.toArray(new Names[transactions.size()]);
如果需要随机化顺序,只需先调用
Collections.shuffle()
即可:Collections.shuffle(transactions);