gpt4 book ai didi

java - 将链表复制到数组

转载 作者:太空宇宙 更新时间:2023-11-04 11:33:34 25 4
gpt4 key购买 nike

我如何像我的老师所说的那样“将链接列表复制到无序数组”?我不知道是否应该使用迭代器,但迭代器不只是将链表复制到另一个链表吗?欢迎任何帮助。

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);

关于java - 将链表复制到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43524065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com