简体   繁体   中英

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

I am trying to implement addFirst to a singly linked list in Java. For some reason my implementation does not print out the linked list correctly. I prdict the problem is in either the addFirst, get, or toString methods. Any help would be greatly appreciated. Thanks in advance. I predict that i am not creating the nodes correctly and I would appreciate an extra eye to spot what I am missing


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);
        }
    }

You have a bug in the constructor of the Node class:

       public Node(E e) 
       { 
           e = value; 

should be

       public Node(E e) 
       { 
           value = e; 

Also, assuming this is the method that you've added:

     * 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++;
        }
    }

You don't really have to differentiate between the cases when the list is empty or otherwise.

You could:

  1. Create a new node
  2. Chain the current head to this newly created node
  3. Set the head to the newly created node
  4. Handle updates to other auxiliary variables, eg size in this case
     * 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++;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM