如何运行此链接列表程序?

时间:2015-04-21 14:43:38

标签: java

 package uni;

    import java.util.*;

    public class Link {

        public int data;
        public Link next;
        int iData;
        Link header = null;
        Link idata;

        public Link(int data) {
            this.data = data;
        }

        public void LinkDisplay() {
            System.out.println("Data: " + data);
        }

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            LinkedList linkedList = new LinkedList();

            int num;
            for (int i = 0; i < 3; i++) {
                System.out.println("Enter data");
                num = input.nextInt();
                linkedList.insertLink(num);
            }

            linkedList.DiaplayAll();
            linkedList.deleteFirst();

        }

    }

    class LinkedList {

        public Link first;
        Link header = null;

        public void insertLink(int data) {
            Link newLink = new Link(data);
            newLink.next = first;
            first = newLink;
        }

        public void DiaplayAll() {
            Link current = first;
            while (current != null) {
                current.LinkDisplay();
                current = current.next;
            }
        }
// delete method is called

        public int deleteFirst() // delete first item
        {
    // (assumes list not empty)
            Link current = header; // save reference to link
            header = header.next; // delete it: first-->old next
            return current.data; `enter code here`// return deleted link
        }

  }

这是Link List程序。我已经多次运行此代码,但它在第45行和第74行中给出了异常。除删除方法外,代码运行良好。可能有两个错误;删除方法调用中的第1个,删除节点时的第二个。

请指导我这些错误是什么以及发生的原因。


这是输出:

debug:
Enter data
100
Enter data
45
Enter data
10
Data: 100
Exception in thread "main" java.lang.NullPointerException
    at uni.LinkedList.deleteFirst(Link.java:74)
    at uni.Link.main(Link.java:45)
Java Result: 1

1 个答案:

答案 0 :(得分:1)

您的列表可能只包含一个header节点,您应该在删除节点时进行检查:

public int deleteFirst() {
    if (header == null)
        return -1;      // <- -1 indicates that list is empty, but it is better to throw RuntimeException here
    Link current = header; 
    header = header.next == null ? null : header.next; // <- check if header.next exists
    return current.data; 
}