Convert a singly linked list to a doubly linked list

Jack

enter image description here Here's the code that I currently have. Only contains the addFirst method.

public void addFirst(E e) {     
    Node<E> newNode = new Node<E>(e); 
    if (tail == null)           
        head = tail = newNode; 
    else {
        newNode.next = head;    
        head = newNode;         
    }
    size++;
}

private static class Node<E> {  
        E element;
        Node<E> next;

        public Node(E e) {
            element = e;
      }
}

Trying to set up the 'previous' field

public void addFirst(E e) {     
    Node<E> newNode = new Node<E>(e); 
    if (tail == null)           
        head = tail = newNode; 
    else {
        newNode.next = head;
        firstElement.previous = newNode; //*
        head = newNode;
        newNode.previous = null;
    }
    size++;
}

private static class Node<E> {  
        E element;
        Node<E> next, previous; //adding previous field

        public Node(E e) {
            element = e;
      }
}

*I want firstElement.previous to point to newNode. How do I do that?

Hector Montero

change:

firstElement.previous = newNode

to

head.previous = newNode;

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related