从链接列表中删除节点(Java)

时间:2014-11-10 05:05:14

标签: java nodes

我正在尝试编写remove(T项)和T remove(int index)函数。 remove(T item)删除您输入的节点。 T remove(int index)从您输入的索引中删除节点。我尝试编写删除函数的每一种方式都会出错。有关如何入门的任何想法?

我试着写这个。当我编译它时似乎不起作用。

    public boolean remove(T item) { 
        if(first==null)
            System.out.println("The List Is Empty");
        else{
            Node<T> current = first;
            Node<T> previous = current.getPrevious();
            while(current!=null && !current.getData().equals(item)){
                previous=current;
                current=current.getNext();
            }
            if(current == first && current.getData().equals(item)){
                first = first.getNext();
            }else if(current != null)
                previous.setNext(current.getNext());
        }

        size--;
        return true;
    }

这是代码。

public class LinkedList<T> implements Iterable<T> {
    private int size = 0;
    private Node<T> first = null,
                    last = null;

    class Node<T> {
        private T data;
        private Node<T> next = null;
        private Node<T> previous = null;

        public Node(T item) {
            data = item;
        }

        public T getData() { return data; }
        public void setData(T data) { this.data = data; }
        public Node<T> getNext() { return next; }
        public void setNext(Node<T> next) { this.next = next; }
        public Node<T> getPrevious() { return previous; }
        public void setPrevious(Node<T> previous) { this.previous = previous; }
    }

    public LinkedList() {
        first = new Node<T>(null);  // no data in first
        last = new Node<T>(null);   // no data in last
        first.setNext(last);
        last.setPrevious(first);
    }
    public String toString() {
        StringBuilder build = new StringBuilder("[");
        Node<T> current = first;
        while (current.getNext() != last) {
            current = current.getNext();
            build.append(current.getData());
            if (current.getNext() != last)
                build.append(", ");
        }
        return build.toString() + "]";
    }

    public int size() { return size; }

    // add an item at the end of the list
    public void add(T item) {
        Node<T> newNode = new Node<T>(item);
        Node<T> nextToLast = last.getPrevious();
        nextToLast.setNext(newNode);
        newNode.setPrevious(nextToLast);
        newNode.setNext(last);
        last.setPrevious(newNode);
        size++;
    }

    // add an item at any position other than the end
    // adds such the new item is at position "index" after
    // add is done
    public void add(int index, T item) {
        Node<T> current = first;
        Node<T> newNode = new Node<T>(item);
        for (int i=0; i<= index; i++)
            current = current.getNext();
        Node<T> previous = current.getPrevious();
        previous.setNext(newNode);
        newNode.setPrevious(previous);
        current.setPrevious(newNode);
        newNode.setNext(current);
        size++;
    }

    public T set(int index, T item) {
        if (index >= size) throw new ArrayIndexOutOfBoundsException();
        Node<T> current = first.getNext(); // before it was first;
        for (int i=0; i<index; i++)
            current = current.getNext();
        T answer = current.getData();
        current.setData(item);
        return answer;
    }

    public boolean remove(T item) {     

        return true;
    }

    public T remove(int index) {




        return null;
    }

    public boolean contains(T item) {



        return false;
    }

    public T get(int index) {


        return null;
    }

    // this is the code from the singly linked list implementation,
    // and without empty first and last nodes.
    public Iterator<T> iterator() {
        return new Iterator<T>( ) {
            private Node<T> current = null, previous = null;

            public boolean hasNext() {
                return current != last;
            }

            public T next() {
                previous = current;
                if (current == null) current = first;
                else current = current.getNext();
                return current.getData();
            }

            public void remove() {
                if (current == null)
                    throw new IllegalStateException();
                if (previous == null)
                    first = current.getNext();
                else {
                    previous.setNext(current.getNext());
                    if (current == last)
                        last = previous;
                    current = previous;
                    previous = null;
                }
                size--;
            }
        };
    }

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        LinkedList<Double> theList = new LinkedList<Double>();
        int choice = -1;
        int index;
        do {
            System.out.println("The list is " + theList);
            System.out.println("Enter a choice between 1 and 9");
            System.out.println("1 = add 2 = addindex 3 = set 4 = remove");
            System.out.println("5 = removeindex 6 = contains 7 = get 8 = Iterator");
            System.out.println("9 = Iterator remove");
            choice = console.nextInt();
            switch(choice) {
            case 1:
                System.out.println("Number");
                theList.add(console.nextDouble());
                break;
            case 2:
                System.out.println("Index");
                index = console.nextInt();
                System.out.println("Number");
                theList.add(index, console.nextDouble());
                break;
            case 3:
                System.out.println("Index");
                index = console.nextInt();
                System.out.println("Number");
                theList.set(index, console.nextDouble());
                break;
            case 4:
                System.out.println("Number");
                theList.remove(console.nextDouble());
                break;
            case 5:
                System.out.println("Index");
                index = console.nextInt();
                theList.remove(index);
                break;
            case 6:
                System.out.println("Number");
                System.out.println(theList.contains(console.nextDouble()));
                break;
            case 7:
                System.out.println("Index");
                System.out.println(theList.get(console.nextInt()));
                break;
            case 8:
                System.out.print("Output using Iterator: [");
                for (Iterator<Double> it = theList.iterator(); it.hasNext(); ) {
                      System.out.print(it.next());
                      if (it.hasNext())
                        System.out.print(", ");
                      else
                        System.out.println("]");
                }
                break;
            case 9:
                System.out.println("Index");
                index = console.nextInt();
                Iterator<Double> i = theList.iterator();
                for (int x=0; x<index; x++)
                    i.next();
                i.remove();
                System.out.println(theList);
            default:
                System.out.println("Enter a choice between 1 and 9");
            }
        } while (choice != -1);
    }
}

1 个答案:

答案 0 :(得分:0)

在您的构造函数中,您正在初始化first&amp; last节点包含null个数据。

public LinkedList() {
    first = new Node<T>(null);  // no data in first
    last = new Node<T>(null);   // no data in last
    first.setNext(last);
    last.setPrevious(first);
}

remove(T item)实现中,您正在检查first是否为null(由于构造函数而不是真的)。​​

因此代码将进入else块并且在first节点中数据为空,因此您将获得NPE @以下行:

  1. while(current!=null && !current.getData().equals(item)){
  2. if(current == first && current.getData().equals(item)){
  3. previous.setNext(current.getNext());
  4. 您需要通过正确的数据验证来修复constructor(删除不必要的变量初始化)以及remove方法。

    仅供参考:您应该为每种方法都有测试用例来捕获这些问题。