2017-04-20 43 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);