欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

站在Java的角度看LinkedList

程序员文章站 2022-06-04 19:32:13
...

站在Java的角度看,玩队列不就是玩对象引用对象嘛!

 

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

 单链表反转:

/**  
     * 递归,在反转当前节点之前先反转后续节点  
     */  
    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;  
    }  
  
    /**  
     * 遍历,将当前节点的下一个节点缓存后更改当前节点指针  
     *   
     */  
    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;  
        }  
        //将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head     
        head.setNextNode(null);  
        head = pre;  
          
        return head;  
    }

 对于数组问题,一般我们要新建数组,必要时移动下标

相关标签: LinkedList