将单链表转换为双链表

时间:2015-03-29 22:22:34

标签: java doubly-linked-list

enter image description here 这是我目前拥有的代码。仅包含addFirst方法。

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

尝试设置之前的&#39;字段

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

*我希望firstElement.previous指向newNode。我该怎么做?

1 个答案:

答案 0 :(得分:1)

变化:

firstElement.previous = newNode

head.previous = newNode;