A detailed example of java LinkedList

  • 2020-09-28 08:54:33
  • OfStack

Details of java LinkedList

From Java's point of view, playing queues is just playing with object references.

Example code:


public class LinkedList<E> implements List<E>, Deque<E> { 
 Node<E> first; 
 Node<E> last; 
 int size; 
 
 public boolean add(E e) { 
    final Node<E> l = last; 
    final Node<E> newNode = new Node<>(l, e, null); 
    last = newNode; 
    if (l == null) 
      first = newNode; 
    else 
      l.next = newNode; 
    size++; 
    modCount++; 
    return true; 
  } 
 
 private static class Node<E> { 
    E item; 
    Node<E> next; 
    Node<E> prev; 
 
    Node(Node<E> prev, E element, Node<E> next) { 
      this.item = element; 
      this.next = next; 
      this.prev = prev; 
    } 
  }  
} 

Single linked list reverse:


/**  
   *  Recursion: Reverses the current node before reversing the subsequent node   
   */  
  public static Node reverse(Node head) {  
    if (null == head || null == head.getNextNode()) {  
      return head;  
    }  
    Node reversedHead = reverse(head.getNextNode());  
    head.getNextNode().setNextNode(head);  
    head.setNextNode(null);  
    return reversedHead;  
  }  
  
  /**  
   *  Traversal, under the current node 1 Changes the current node pointer after five nodes are cached   
   *  
   */  
  public static Node reverse2(Node head) {  
    if (null == head) {  
      return head;  
    }  
    Node pre = head;  
    Node cur = head.getNextNode();  
    Node next;  
    while (null != cur) {  
      next = cur.getNextNode();  
      cur.setNextNode(pre);  
      pre = cur;  
      cur = next;  
    }  
    // Put the original list under the header node 1 0, 0, 0, 0 null , and assigns the reversed header node to head    
    head.setNextNode(null);  
    head = pre;  
      
    return head;  
  } 

For the array problem, 1 we usually create a new array and move the subscripts if necessary

The above is the example of java LinkedList, if you have any questions, please leave a message or go to this site for community exchange and discussion, thank you for reading, hope to help you, thank you for your support to this site!


Related articles: