一聚教程网:一个值得你收藏的教程网站

热门教程

java LinkedList的实例详解

时间:2022-06-29 01:21:45 编辑:袖梨 来源:一聚教程网

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

实例代码:

publicclassLinkedListimplementsList, Deque {
 Node first;
 Node last;
 intsize;
  
 publicbooleanadd(E e) {
    finalNode l = last;
    finalNode newNode =newNode<>(l, e,null);
    last = newNode;
    if(l ==null)
      first = newNode;
    else
      l.next = newNode;
    size++;
    modCount++;
    returntrue;
  }
  
 privatestaticclassNode {
    E item;
    Node next;
    Node prev;
  
    Node(Node prev, E element, Node next) {
      this.item = element;
      this.next = next;
      this.prev = prev;
    }
  } 
}

单链表反转:

/** 
   * 递归,在反转当前节点之前先反转后续节点 
   */ 
  publicstaticNode reverse(Node head) { 
    if(null== head ||null== head.getNextNode()) { 
      returnhead; 
    } 
    Node reversedHead = reverse(head.getNextNode()); 
    head.getNextNode().setNextNode(head); 
    head.setNextNode(null); 
    returnreversedHead; 
  } 
   
  /** 
   * 遍历,将当前节点的下一个节点缓存后更改当前节点指针 
   * 
   */ 
  publicstaticNode reverse2(Node head) { 
    if(null== head) { 
      returnhead; 
    } 
    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; 
       
    returnhead; 
  }

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

热门栏目