2017-04-20 139 views
1

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

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

你为什么不问他们? – tnw

+0

一个无序数组就是你在其上调用Collections.shuffle()的地方。 – satnam

+0

循环遍历'LinkedList'并将每个元素添加到'Array'。 – brso05

回答

0

您可以在一行代码中执行此操作。

假设你有一个这样的名单:

List<Names> transactions; 

将其转换为一个数组简单地做:

Names[] transactionsArray = transactions.toArray(new Names[transactions.size()]); 

如果您需要随机的顺序,只需拨打Collections.shuffle()第一:

Collections.shuffle(transactions); 
相关问题