我已經完成了將代碼添加到LinkedList
中的代碼。現在我想按排序順序將元素插入到列表中。我怎樣才能做到這一點?添加方法應該按排序順序將元素插入到列表中
public void add(String element)
{
if (isEmpty())
{
first = new Node(element);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(element);
last = last.next;
}
}
我的主類是本作的LinkedList和ArrayList這就要求SimpleLinkedList
類的方法和SimpleArrayListClass
package Comp10152_linkedlist;
import java.util.Random;
public class Comp10152_Lab4
{
public static void main(String[] args)
{
final int NUMBER_OF_ITERATIONS = 10;
String names[] = {"Amy", "Bob", "Al", "Beth", "Carol", "Zed", "Aaron"};
SimpleLinkedList ll = new SimpleLinkedList();
final int TOTALOPERATIONS = names.length * NUMBER_OF_ITERATIONS;
Random random = new Random();
for (int i=0; i<NUMBER_OF_ITERATIONS;i++)
{
for (int j=0; j<names.length; j++)
ll.add(names[j]);
}
System.out.println("The members of list are:");
System.out.println(ll);
// remove half of the items in the list by selecting randomly from names
for (int i=0; i<TOTALOPERATIONS/2;i++)
{
ll.remove(names[random.nextInt(names.length)]);
}
System.out.println("The members of list are:");
System.out.println(ll);
SimpleArrayList al = new SimpleArrayList();
try
{
for (int i=0; i<NUMBER_OF_ITERATIONS;i++)
{
for (int j=0;j<names.length;j++)
al.add(i,names[j]);
}
System.out.println("The members of array are:");
System.out.println(al);
// remove half of the items in the list by selecting randomly from names
for (int i=0; i<TOTALOPERATIONS/2;i++)
{
al.remove(names[random.nextInt(names.length)]);
}
System.out.println("The members of array are:");
System.out.println(al);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
異常在線程 「主」 顯示java.lang.NullPointerException \t在Comp10152_linkedlist.SimpleLinkedList.add(SimpleLinkedList.java:108) \t在Comp10152_linkedlist.Comp10152_Lab4.main(Comp10152_Lab4 .java:30) – 2014-11-05 05:33:07
和currentNode ????? – 2014-11-05 05:33:35
和「currentNode.next.element」在你使用哪個元素? – 2014-11-05 05:35:40