我的程序旨在获取单词列表并将每个单词按升序存储在数组中的字母引用下。例如 AZ 单词数组 apple,A 下的链表下的猿由 0 引用,Z 下的 Zebra 由 25 引用。但是当我使用标准 first = new Node(word) 时,我没有添加任何内容。我绝望地迷失了。
import java.util.LinkedList;
public class ArrayLinkedList
{
/**
The Node class is used to implement the
linked list.
*/
private class Node
{
String value;
Node next;
/**
* Constructor
* @param val The element to store in the node
* @param n The reference to the successor node
*/
Node(String val, Node n)
{
value = val;
next = n;
}
Node(String val)
{
this(val, null);
}
}
private final int MAX = 26; // Number of nodes for letters
private Node first; // List head
private Node last; // Last element in the list
private LinkedList[] alpha; // Linked list of letter references
/**
* Constructor to construct empty array list
*/
public ArrayLinkedList()
{
first = null;
last = null;
alpha = new LinkedList[MAX];
for (int i = 0; i < MAX; i++)
{
alpha[i] = new LinkedList();
}
}
/**
* arrayIsEmpty method
* To check if a specified element is empty
*/
public boolean arrayIsEmpty(int index)
{
return (alpha[index].size() == 0);
}
/**
* The size method returns the length of the list
* @return The number of elements in the list
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count++;
p = p.next;
}
return count;
}
/**
* add method
* Adds the word to the first position in the linked list
*/
public void add(String e)
{
String word = e.toLowerCase(); // Put String to lowercase
char c = word.charAt(0); // to get first letter of string
int number = c - 'a'; // Index value of letter
// Find position of word and add it to list
if (arrayIsEmpty(number))
{
first = new Node(word);
first = last;
}
else
{
first = sort(first, word, number);
}
}
/**
* nodeSort method
* To sort lists
*/
private Node sort(Node node, String value, int number) {
if (node == null) // End of list
{
return getNode(value, number);
}
int comparison = node.value.compareTo(value);
if (comparison >= 0) // Or > 0 for stable sort.
{
Node newNode = getNode(value, number); // Insert in front.
newNode.next = node;
return newNode;
}
node.next = sort(node.next, value, number); // Insert in the rest.
return node;
}
private Node getNode(String value, int number)
{
return first.next;
}
/**
* get method
* to get each word value from the linked list and return it
* @return value
*/
public LinkedList get(int index)
{
return alpha[index];
}
public String toString()
{
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("Word and occurrence in ascending order\n\n");
Node p = first;
while (p != null)
{
sBuilder.append(p.value + "\n");
p = p.next;
}
return sBuilder.toString();
}
}