如何将文本文件中的单词添加到单个链接列表中

时间:2012-03-13 20:38:03

标签: java linked-list text-files

此分配的对象是将文件列表从文件输出到单个链接列表中,然后按字母顺序对它们进行排序。但是我无法弄清楚如何将单个单词放入链表中。我是非常新的,任何提示或提示都将非常感激。

以下是我认为正确的Node课程:

//Node of a singly linked list of strings
public class Node {
   private String element;
   private Node next;

   //creates a node with the given element and next

   public Node(String s, Node n){
      element = s;
      next = n;
   }

   //Returns the elements of this
   public String getElement(){
      return element;
   }
   public Node getNext(){
      return next;
   }

   //Modifier
   //Sets the element of this
   public void setElement(String newElement){
      element = newElement;
   }

   //Sets the next node of this
   public void setNext(Node newNext){
      next = newNext;
   }
}

这是我的主要课程,它从文件中取出句子并将其分解为单个单词。那是我有一个问题,我无法弄清楚如何将个人的单词放入链表:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class DictionaryTester{
  public static void main(String[] args) {
    try {
      BufferedReader br = new BufferedReader(new FileReader("input1"));
      String file;
      int lineNum = 1;
      while ((file = br.readLine()) != null) {
        System.out.print( "(" + lineNum++ + ") ");
        System.out.println(file.toLowerCase());

        String line = br.readLine();
        //String is split or removes the spaces and places into the array words
        String[] words = line.split(" ");

        //for loop to keep running on the length of the array
        for(int i =0; i< words.length; i++){
          //word is equal to a particular indexed spot of the word array and gets rid of all non-alphabet letters
          String word = words[i];
          word = word.replaceAll("[^a-z]", "");
        }
      }
    }
    catch (IOException e){
      System.out.println("Error: " + e.getMessage());
    }
  }
}

我所拥有的另一个课程是SLinkedList,它会将单词保留在列表中,但就像我说我无法弄清楚如何将单个单词放入列表中:

//Singly linked list
public class SLinkedList {
   //head node of the list
   protected Node head;

   //number of nodes in the list
   protected long size;

   //Default constructor that creates an empty list
   public SLinkedList(){
      head = null;
      size = 0;
   }
}

我知道如何插入单链表的元素,但是试图将单词列入列表已经证明对我来说很难。任何事都对我很有帮助。

2 个答案:

答案 0 :(得分:0)

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

  

扫描仪还可以使用空格以外的分隔符。这个   示例从字符串中读取几个项目:

 String input = "1 fish 2 fish red fish blue fish";
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
 System.out.println(s.nextInt());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.next());
 s.close();

循环直到文件末尾,缓存当前单词,并将其插入当前节点。然后移动到链接中的下一个节点,并重复。

完成后,您将不得不进行某种排序并交换节点。

答案 1 :(得分:0)

试试这个,希望这对你有用......

'Socialite' => Laravel\Socialite\Facades\Socialite::class,