簡體   English   中英

Java中單鏈表中addFirst方法的實現返回null?

[英]Implementation of addFirst method in singly linked list in Java returns null?

我正在嘗試將 addFirst 實現到 Java 中的單鏈表。 由於某種原因,我的實現沒有正確打印出鏈表。 我預測問題出在 addFirst、get 或 toString 方法中。 任何幫助將不勝感激。 提前致謝。 我預測我沒有正確創建節點,我希望能多看一眼發現我缺少的東西


import java.util.Iterator;

/**
 * A basic singly linked list implementation.
 */
public class SinglyLinkedList<E> implements Cloneable, Iterable<E>, List<E> {
    //---------------- nested Node class ----------------

    /**
     * Node of a singly linked list, which stores a reference to its
     * element and to the subsequent node in the list (or null if this
     * is the last node).
     */
    private static class Node<E> {
       E value;
       Node<E> next;
       public Node(E e) 
       { 
           e = value; 
           next = null; 
       } 
    }
    
    //----------- end of nested Node class -----------

    // instance variables of the SinglyLinkedList
    private Node<E> head = null; // head node of the list (or null if empty)

    private int size = 0; // number of nodes in the list

    public SinglyLinkedList() {
    }              // constructs an initially empty list

    // access methods

    /**
     * Returns the number of elements in the linked list.
     *
     * @return number of elements in the linked list
     */
    public int size() {
        return size;
    }

    /**
     * Tests whether the linked list is empty.
     *
     * @return true if the linked list is empty, false otherwise
     */
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public E get(int i) throws IndexOutOfBoundsException {
        if(i>this.size()) {
            int count = 0;
            Node<E> a = head;
            while(count != i) {
                count ++;
                System.out.println(a.value);
                a = a.next;
            }
        }
        return null;
    }

    @Override
    public E set(int i, E e) throws IndexOutOfBoundsException {
        return null;
    }

    @Override
    public void add(int i, E e) throws IndexOutOfBoundsException {

    }

    @Override
    public E remove(int i) throws IndexOutOfBoundsException {
        return null;
    }

    /**
     * Returns (but does not remove) the first element of the list
     *
     * @return element at the front of the list (or null if empty)
     */
    public E first() {
        // TODO
        return null;
    }

    /**
     * Returns the last node of the list
     *
     * @return last node of the list (or null if empty)
     */
    public Node<E> getLast() {
        // TODO
        return null;
    }

    /**
     * Returns (but does not remove) the last element of the list.
     *
     * @return element at the end of the list (or null if empty)
     */
    public E last() {
        // TODO
        return null;
    }

    // update methods

    /**
     * Adds an element to the front of the list.
     *
     * @param e the new element to add
     */
    public void addFirst(E e) {
        if(this.size() == 0) {
         Node<E> first = new Node<E>(e);
        this.size++;
        this.head = first;
        } else {
            Node<E> first = new Node<E>(e);
            first.next = this.head;
            this.head = first;
            this.size++;
        }
    }

    /**
     * Adds an element to the end of the list.
     *
     * @param e the new element to add
     */
    public void addLast(E e) {
        // TODO
    }

    /**
     * Removes and returns the first element of the list.
     *
     * @return the removed element (or null if empty)
     */
    public E removeFirst() {
        // TODO
        return null;
    }

    @SuppressWarnings({"unchecked"})
    public boolean equals(Object o) {
        // TODO
        return false;   // if we reach this, everything matched successfully
    }

    @SuppressWarnings({"unchecked"})
    public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
        // TODO
        return null;
    }


    /**
     * Produces a string representation of the contents of the list.
     * This exists for debugging purposes only.
     * @return 
     */
    public String toString() {
        for(int i=0;i<this.size();i++) {
            System.out.println(this.get(i));
        }
        return "end of Linked List";
    }

    private class SinglyLinkedListIterator<E> implements Iterator<E> {
        @Override
        public boolean hasNext() {
            // TODO
            return false;
        }

        @Override
        public E next() {
            // TODO
            return null;
        }
    }

    public Iterator<E> iterator() {
        return new SinglyLinkedListIterator<E>();
    }

    public static void main(String[] args) {
        //ArrayList<String> all;
        //LinkedList<String> ll;
        /*SinglyLinkedList<String> sll = new SinglyLinkedList<String>();

        String[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");

        for (String s : alphabet) {
            sll.addFirst(s);
            sll.addLast(s);
        }
        System.out.println(sll.toString());

        for (String s : sll) {
            System.out.print(s + ", ");
        }
        */
            SinglyLinkedList <Integer> ll =new SinglyLinkedList <Integer>();
            ll.addFirst(1);
            ll.addFirst(3);
            System.out.println(ll);
        }
    }

您在Node class 的構造函數中有一個錯誤:

       public Node(E e) 
       { 
           e = value; 

應該

       public Node(E e) 
       { 
           value = e; 

另外,假設這是您添加的方法:

     * Adds an element to the front of the list.
     *
     * @param e the new element to add
     */
    public void addFirst(E e) {
        if(this.size() == 0) {
         Node<E> first = new Node<E>(e);
        this.size++;
        this.head = first;
        } else {
            Node<E> first = new Node<E>(e);
            first.next = this.head;
            this.head = first;
            this.size++;
        }
    }

您實際上不必區分列表為空或其他情況的情況。

你可以:

  1. 創建一個新節點
  2. 將當前頭部鏈接到這個新創建的節點
  3. 將頭部設置為新創建的節點
  4. 處理對其他輔助變量的更新,例如在這種情況下的大小
     * Adds an element to the front of the list.
     *
     * @param e the new element to add
     */
    public void addFirst(E e) {
        Node<E> first = new Node<>(e);
        first.next = this.head;
        this.head = first;
        this.size++;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM