public static void main (String[] args)
{
Student st1 = new Student("Adams", 3.6, 26);
Student st2 = new Student("Jones", 2.1, 29);
Student st3 = new Student("Marcus", 4.0, 53);
System.out.println("Testing non-recursive code");
LinkedListStud LL = new LinkedListStud();
//checks if linked list is empty
System.out.println("Linked list is empty?: " + LL.isEmpty());
//adds students to the linked list from the front
LL.addFront(st3);
LL.addFront(st2);
LL.addFront(st1);
//adds students to the linked list from the back
LL.addTail(st1);
LL.addTail(st2);
LL.addTail(st3);
//prints linked list non-recursively
LL.printLL();
System.out.println("Linked list is empty?: " + LL.isEmpty());
}
这是我的测试方法^,你可以看到我正在用学生对象填充我的列表。printLL()方法显示所有6个对象实际上都在数组中。
public boolean isEmpty()
{
Boolean e;
if (list==null)
return e=true;
else
return e=false;
}
这是我的isEmpty()方法。参数和数据类型由我的教授指定。由于某种原因,我的列表总是等于null,即使它应该包含6个对象,我第二次使用该方法。我错过了什么?
我的整个链表类
public class LinkedListStud
{
private Node list;
public LinkedListStud()
{
list = null;
}
public void addFront(Student s)
{
Node oneNode = new Node(s);
oneNode.next=list;
list=oneNode;
}
public void addTail(Student s)
{
Node current;
Node oneNode = new Node(s);
if (list==null)
list=oneNode;
else
{
current=list;
while (current.next != null)
current=current.next;
current.next=oneNode;
}
}
public boolean isEmpty()
{
Boolean e=true;
if (list!=null)
return false;
else
return e;
}
public Student bestStudent()
{
Student bestStudent=list.data;
while (list.next!=null)
{
if (list.next.data.getGpa()>list.data.getGpa())
{
Student temp = list.data;
list.data=list.next.data;
list.next.data=temp;
}
list=list.next;
}
return bestStudent;
}
public void printLL()
{
while (list!=null)
{
System.out.println(list.data);
list=list.next;
}
}
public void printLLRec(Node list)
{
if (list!=null)
{
System.out.println(list.data);
printLLRec(list.next);
}
}
Student bestStudRec(Node list)
{
Student bestStudent = list.data;
if (list!=null)
{
if (list.next.data.getGpa()>list.data.getGpa())
{
bestStudent=list.next.data;
bestStudRec(list.next);
}
}
return bestStudent;
}
private class Node
{
public Student data;
public Node next;
public Node(Student s)
{
data=s;
next=null;
}
public String toString()
{
return "" + data;
}
}
}
问题在这里:
public void printLL()
{
while (list!=null)
{
System.out.println(list.data);
list=list.next;
}
}
用嵌套的列表替换列表变量,直到它变为空。最后一次迭代设置了你的LL。列表为空,然后while检查它并输出。如果你像这样修改while:
public void printLL()
{
while (list!=null)
{
System.out.println(list.data);
if (list.next == null) break;
list=list.next;
}
}
你将得到你需要的,但是你的根LL将从上一个节点替换值。
根据@Vadim的回答,如果您想在不更改内部列表的情况下将其打印出来,则可以引入一个局部变量。
public void printLL()
{
Node temp = list;
while (temp!=null)
{
System.out.println(temp.data);
temp=temp.next;
}
}