【问题标题】:Java Doubly linked list addLast() and removelast() methodJava 双向链表 addLast() 和 removelast() 方法
【发布时间】:2021-03-25 04:52:01
【问题描述】:

我正在使用 java 处理双向链表,它们维护对一个的引用 称为“哨兵节点”或“nil”的特殊节点。我只有一个构造函数来创建空列表。

我的 addlast 类是将 elem 添加到列表的末尾。当我测试我的代码时,控制台一直说“无法读取字段“next”,因为“this.tail”为空” 谁能解释一下为什么以及如何解决它?

例如: 在 DList.addLast(DList.java:79) 在 DList.main(DList.java:205)

import java.util.*;

public class DList implements Iterable<String> {
    
        private static class DListNode {
        public String data;
        public DListNode next;
        public DListNode previous;       
        }
        
        //Returns an iterator over the list as inner class
        private class DListIterator implements Iterator<String> {
             private DListNode pointer;

             public DListIterator() {
             if(nil.next ==nil)
             pointer = nil;
             else
             pointer = nil.next;             
             }

            public boolean hasNext() {
                return pointer.next!=null;
            }

            public String next() {
                if (!hasNext()) 
                    throw new NoSuchElementException();
                return pointer.next.data;
            }
        }
         
        private DListNode nil;
        private DListNode head;
        private DListNode tail;
        private int numElements;
        
         //create empty list.
        public DList() {
            nil = new DListNode();
            nil.previous = nil;
            nil.next = nil;
            nil.data = null;
            numElements = 0;
        }
        
        /*
         * //create list with element. public DList(String elem) { DListNode temp = new
         * DListNode(); this.tail = this.head = temp; numElements = 1; }
         */
        
        //adds elem to the front of the list
        public void addFirst(String elem) {
             DListNode newHead = new DListNode();
             newHead.data = elem;
             newHead.next = head;
             newHead.previous = nil;
             
             if(head==null)
                 head = newHead;
             else {
                 head.previous = newHead;
             }
             head = newHead;
             numElements++;
        }
         
        //adds elem to the end of the list
        public void addLast(String elem) {
            DListNode newTail = new DListNode();
    
            newTail.data = elem; 
            newTail.previous = tail;
              
              //If the Linked List is empty, then make the new node as head 
             if (head == nil) 
                 head = tail = newTail;
             else { //Change the next of last node
                 newTail = tail.next;
                 tail = newTail;
              } 
            tail = newTail;
            
            numElements++;
        }
        
        //get the first value from node
        public String getFirst() {          
            if(head==nil)
                throw new NoSuchElementException("This is empty node.");
            return head.data;
        }

        //get the last value from node
        public String getLast() {
            DListNode last = head; 
            while (last.next != null)
                last = last.next;
            
            if(last==null)
                throw new NoSuchElementException("This is empty node.");
            return last.data;
        }
        
        //get value of particular index
        public String get(int index) { 
            //looking start at index 0
            DListNode current = head;
    
            if(index<0 || index>numElements) 
                throw new IndexOutOfBoundsException("The index is out of bound");
            else {
                for(int i=0; i<index; i++)
                    current = current.next;
            }
            return current.data;   
        }
         
        //changes the value at “position” index and returns the old value
        public String set(int index, String value) {
            DListNode temp = new DListNode();
            if(index<0 || index>numElements) 
                throw new IndexOutOfBoundsException("The index is out of bound");
            else {
                DListNode current = head;
                for (int i = 0; i < index; i++) {
                    current = current.next;
                }
                DListNode previous = current.previous;
                previous.next = temp;
                temp.previous = previous;
                temp.next = current;
                current.previous = temp;
                numElements++;
                return temp.data;
            }
        }
        
        //Returns true if obj appears in the list and false otherwise. 
        public boolean contains(Object obj) {
            return nil.data.equals(obj);
        }
        
        //Returns the index of obj if it is in the list and -1 otherwise
        public int indexOf(Object obj) {
            if(contains(obj))
                get(numElements);
            return -1;
        }
        
        public int size() {
            return numElements;
        }
        
        public String toString() {
            String result = " ";
            DListNode temp = head;

            while(temp!=null) {
                result += temp.data + " ";
                temp = temp.next;
            }
        return result;
        }

        //removes the front element of the list and return it
        public String removeFirst() {
            if(size()==0)
                throw new NoSuchElementException();
            DListNode tmp = head;
            head = head.next;
            head.previous = nil;
            numElements--;
            return tmp.data;
        }
        
        //removes the last element of the list and returns it
        public String removeLast() {
            if(size()==0)
                throw new NoSuchElementException();
            DListNode tmp = tail;
            tail = tail.next;
            tail.next = nil;
            numElements--;
            return tmp.data;
        }
            
        //Returns an iterator over the list. 
         public Iterator<String> iterator() {
            return new DListIterator();
         }
        
        
        public static void main(String[] args) {  
            //create a DoublyLinkedList object
            DList dl_List = new DList();
        
            //Check the addFirst method
            dl_List.addFirst("is");
            System.out.println(dl_List);        
            dl_List.addFirst("This");
            System.out.println(dl_List);
            
            //Check the addLast method
            dl_List.addLast("Doubly");
            System.out.println(dl_List);        
            dl_List.addLast("linked");
            System.out.println(dl_List); 
            
            //check the getFirst method
            System.out.println(dl_List.getFirst());
            //check the getLast method
            System.out.println(dl_List.getLast());
            
            //test remove method
            dl_List.removeFirst();
            dl_List.removeLast();
            System.out.println(dl_List);
            
            //test get method
            System.out.println(dl_List.get(1));
            
            System.out.println(dl_List.size());
            
        }
}

【问题讨论】:

  • 您可能希望正确缩进和格式化您的代码:告诉您的 IDE 或代码编辑器自动格式化,然后用其他人更容易阅读的内容更新您的帖子。另外,请记住这不是一个通用的帮助论坛,some work by you is expected:你已经做了什么来尝试调试这个?例如,您是否使用调试器模式运行代码?您是否尝试将代码减少到已经出错的最小示例?等

标签: java doubly-linked-list


【解决方案1】:

这是发生在你没有在构造函数中设置tail,所以他变成了null。 要解决这个问题,请在构造函数中设置tail或添加检查语句以检查tail是否不等于null,然后再访问tail.next。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 2016-06-10
    • 2012-03-22
    • 2012-03-23
    相关资源
    最近更新 更多