您好我收到空指針異常從排序方法中的此代碼無法找出原因。我會很感激任何迴應。 它在行號碼93在排序方法下而迴路next = first.next。 由於提前排序元素鏈接列表插入排序Java
public class LinkedList {
Student first,last,match,pointer;
Course start,end;
int linkCount = 1;
public LinkedList(){
first = null;
last = null;
}
public boolean isEmpty(){
return first==null;
}
public void deleteLink(int id){
Student firstnext = first;
if(id==first.id){
Student temp = first.next;
first = temp;
}
else if(last.id==id){
while(first!=null){
if(first.next.id == id){
first.next=null;
}
first = first.next;
}
first = firstnext;
}
else{
while(first.next!=null){
if(first.next.id == id){
first.next = first.next.next;
}
first = first.next;
}
first = firstnext;
}
}
public void traverseStudent(){
Student currentStudent = pointer;
while(currentStudent != null) {
currentStudent.printLink();
currentStudent.traverseCourse();
currentStudent = currentStudent.next;
}
System.out.println("");
}
public void insert(String fname, String lname, int id, String courseId, int credits,char grade){
if(isExist(id)){
match.insertCourse(courseId,credits,grade);
}
else{
Student link = new Student(fname, lname, id);
if(first==null){
link.next = null;
first = link;
last = link;
}
else{
last.next=link;
link.next=null;
last=link;
}
linkCount++;
link.insertCourse(courseId,credits,grade);
}
}
public void sort(){
Student current,next,firstLink = first,temp=null;
int flag = 0,flag2 =0;
pointer = null;
if(first!=null){
if(first.next==null){
current = first;
}
else{
while(linkCount>0){
current = first;
next = first.next;
while(next!=null){
if(current.lName.compareToIgnoreCase(next.lName)>0){
current = next;
if(flag2 == 0)
flag = 1;
}
next = next.next;
}
first = firstLink;
if(flag == 1){
deleteLink(current.id);
current.next = null;
pointer = current;
temp = pointer;
flag =0;
flag2 =1;
}
else if(flag2 ==1){
deleteLink(current.id);
current.next = null;
pointer.next = current;
pointer = pointer.next;
}
linkCount--;
}
}
pointer = temp;
}
}
public boolean isExist(int id){
Student currentStudent = first;
while(currentStudent != null) {
if(currentStudent.id==id){
match = currentStudent;
return true;
}
currentStudent = currentStudent.next;
}
return false;
}
}
你介意和我們這行究竟有NPE共享。 –
在while循環「next = first.next」下的Sort方法中,它的行號爲93。 –