Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

linked list get first &last element?

my program is about doubly linked list and I want to add two method one to get first element and another one to get last element ,these are my codes but when I add any code two this method it give me an error

package doublelinkeddd;

import java.util.NoSuchElementException;

public class DoublyLinkedListImpl<E> {

private Node head;

private Node tail;

private int size;

public DoublyLinkedListImpl() {

size = 0;

}

private class Node {

E element;

Node next;

Node prev;

public Node(E element, Node next, Node prev) {

this.element = element;

this.next = next;

this.prev = prev;

}

}

public boolean isEmpty() { return size == 0; }

public E first(){

}

public E last(){

}

public void addFirst(E element) {

Node tmp = new Node(element, head, null);

if(head != null ) {head.prev = tmp;}

head = tmp;

if(tail == null) { tail = tmp;}

size++;

System.out.println("adding: "+element);

}

public static void main(String a[]){

DoublyLinkedListImpl<Integer> dll = new DoublyLinkedListImpl<Integer>();

dll.addFirst(10);

dll.addFirst(34);

}

}

1 Answer

Relevance
  • 4 years ago

    That compiles just fine, except for the missing return statements in the first() and last() methods.

    The only trick in coding those two is that you need to return a reference to an E type object. If the list is empty, you'll either return null or throw an exception. The first() method might look like:

    E first() {

    .... if (head==null) return null;

    .... return head.element;

    }

    Change the "return null;" to an appropriate throw statement if you need an exception instead of a null result. The last() method is nearly the same.

Still have questions? Get your answers by asking now.