2014-02-22 33 views
0

我試圖將數值表達式的行標記爲CS項目的鏈接列表。我必須使用我在之前的實驗中創建的自己的鏈接列表。將文本從txt文件放入鏈接列表

我標記每行的數字和操作符,並將每個標記插入鏈表中的節點,因爲它們是標記化的。當我編寫程序打印出每個令牌時,每個令牌都被打印出來。但是當我告訴它打印出包含每個令牌的鏈接列表作爲一個節點時,有些操作符會丟失。我不知道這種行爲的原因是什麼。

下面是創建包含每個令牌鏈表中的方法:

public static LinkedListTest ReadInFile(String path){ 
    File file = new File(path); 
    LinkedListTest list = new LinkedListTest(); 

    try { 
     Scanner scanner = new Scanner(file); 
     int count = 0; 

     while (scanner.hasNextLine()) { 
      String line = scanner.nextLine(); 
      StringTokenizer st = new StringTokenizer(line); 
      while (st.hasMoreTokens()){ 
       list.insert(st.nextToken()); 
      } 
     } 
     scanner.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    return list; 
} 

下面是用於插入到一個鏈表並打印一個方法:

public class LinkedListTest implements LinkedList { 
private Node head; 

public LinkedListTest(){ 
    head = new Node(); 
} 

public void insert(Object x){ 
    if (lookup(x) == false){ 

     if (head.data == null) 
      head.data = x; 

     else{ 
     /* 
     Node NewNode = new Node(); 
     NewNode.data = x; 
     NewNode.next = head; 
     head = NewNode; 
     */ 

      //InsertLast 
      Node temp = head; 

      while (temp.next != null){ 
       temp = temp.next; 
      } 

      Node NewNode = new Node(); 
      NewNode.data = x; 
      NewNode.next = null; 

      temp.next = NewNode; 

     } 
    } 
} 

public void printList(){ 
    Node temp = head; 

    while (temp.next != null){ 
     System.out.print(temp.data + " "); 
     temp = temp.next; 
    } 

    System.out.print(temp.data + " "); 
} 
} 

回答

0

我解決它。我的插入函數的查找子句搞砸了。