一个简单的java的 linked list问题
闲暇之中随便写一个java的小程序 但是有错误 实在是找不到 抓狂死了 请大家帮忙 很简单的问题:
就是一个最普通的linked list 插入问题
public class linkList{
class list{
int value;
list next;//=null;
}
list head=null;
public void insert (int num){
list newNode=new list();
list runner;
list previouse;
newNode.value=num;
if(head==null){
head=newNode;
newNode.next=null;
}
else
{
previouse=null;
runner=head;
while(runner.value<num&&runner!=null){
previouse=runner;
runner=runner.next;
}
if(previouse==null){
head=newNode;
newNode.next=runner;
}
else if(runner==null){
previouse.next=newNode;
newNode.next=runner;
}
}
}
public void printList(){
list runner=new list();
if(head==null)
System.out.println("This is an empty list!");
else{
runner=head;
while(runner!=null){
System.out.println(runner.value);
runner=runner.next;
}
}
}
}
main function 在另一个文件:
import java.io.*;
public class driver {
public static void main(String[] args){
int number;
linkList myList=new linkList ();
for(int i=0;i<10;i++){
myList.insert(i);
}
myList.printList();
}
}
不知道为什么就是有错, 如果我插入的顺序是 10, 9, 8, 7,。。。。1 就没事
但如果我要是正着插入1,2,3,4,5.。。。10 就会出错 报错说:
Exception in thread "main"
java.lang.NullPointerException at binaryTree.insert(binaryTree.java:30)
at driver.main(driver.java:10)
我就是不知道为什么 大家快告诉我 让我别再抓狂了。。。
------解决方案-------------------- while (runner != null&&runner.value < num){
previouse = runner;
runner = runner.next;
}
其他逻辑没怎么看,别抓狂了。应该就是这个问题。
------解决方案-------------------- 探讨 while (runner != null&&runner.value < num){ previouse = runner; runner = runner.next; } 其他逻辑没怎么看,别抓狂了。应该就是这个问题。
------解决方案-------------------- at binaryTree.insert(binaryTree.java:30)
binaryTree.java的30行报
空指针 Java code
class list {
int value;
list next;// =null;
}
public class linkList {
list head = null;
public void insert(int num) {
list newNode = new list();
list runner;
list previouse;
newNode.value = num;
if (head == null) {
head = newNode;
newNode.next = null;
} else {
previouse = null;
runner = head;
while (runner != null && runner.value < num) { // 你的写法有点问题,应该先判断是否为null
// 在判断value,因为&&是短路操作符,如果runner为null了,就不会判断.value
// < num,按照你的写法,如果runner为null则会报空指针
previouse = runner;
runner = runner.next;
}
if (previouse == null) {
head = newNode;
newNode.next = runner;
} else if (runner == null) {
previouse.next = newNode;
newNode.next = runner;
}
}
}
public void printList() {
list runner = new list();
if (head == null)
System.out.println("This is an empty list!");
else {
runner = head;
while (runner != null) {
System.out.println(runner.value);
runner = runner.next;
}
}
}
public static void main(String[] args) {
int number;
linkList myList = new linkList();
for (int i = 0; i < 10; i++) {
// for (int i = 10; i > 0; i--) {
myList.insert(i);
}
myList.printList();
}
}