我如何"将您的链接列表复制到无序数组"正如我老师所说的那样?我不知道我是否应该使用迭代器,但迭代器是否只将链表复制到另一个链表?欢迎任何帮助。
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();
}
答案 0 :(得分:0)
您可以在一行代码中执行此操作。
假设您有一个这样的列表:
List<Names> transactions;
要将其转换为数组,只需执行以下操作:
Names[] transactionsArray = transactions.toArray(new Names[transactions.size()]);
如果您需要随机化订单,只需先致电Collections.shuffle()
:
Collections.shuffle(transactions);