欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java 實現(xiàn)單鏈表逆轉詳解及實例代碼

 更新時間:2017年02月28日 09:07:13   作者:lean1252  
這篇文章主要介紹了java 實現(xiàn)單鏈表逆轉實例代碼的相關資料,需要的朋友可以參考下

java 實現(xiàn)單鏈表逆轉詳解

實例代碼:

class Node { 
  Node next; 
  String name; 
  public Node(String name) { 
    this.name = name; 
  } 
 
  /** 
   * 打印結點 
   */ 
  public void show() { 
    Node temp = this; 
    do { 
      System.out.print(temp + "->"); 
      temp = temp.next; 
    }while(temp != null); 
    System.out.println(); 
  } 
 
  /** 
   * 遞歸實現(xiàn)單鏈表反轉,注意:單鏈表過長,會出現(xiàn)StackOverflowError 
   * @param n 
   * @return 
   */ 
  public static Node recursionReverse(Node n) { 
    long start = System.currentTimeMillis(); 
    if(n == null || n.next == null) { 
      return n; 
    } 
    Node reverseNode = recursionReverse(n.next); 
 
    n.next.next = n; 
    n.next = null; 
    System.out.println("遞歸逆置耗時:" + (System.currentTimeMillis() - start) + "ms..."); 
    return reverseNode; 
  } 
 
  /** 
   * 循環(huán)實現(xiàn)單鏈表反轉 
   * @param n 
   * @return 
   */ 
  public static Node loopReverse(Node n) { 
    long start = System.currentTimeMillis(); 
    if(n == null || n.next == null) { 
      return n; 
    } 
 
    Node pre = n; 
    Node cur = n.next; 
    Node next = null; 
    while(cur != null) { 
      next = cur.next; 
      cur.next = pre; 
      pre = cur; 
      cur = next; 
    } 
    n.next = null; 
    n = pre; 
    System.out.println("循環(huán)逆置耗時:" + (System.currentTimeMillis() - start) + "ms..."); 
    return pre; 
  } 
 
  @Override 
  public String toString() { 
    return name; 
  } 
   
  public static void main(String[] args) { 
 
    int len = 10; 
    Node[] nodes = new Node[len]; 
    for(int i = 0; i < len; i++) { 
      nodes[i] = new Node(i + ""); 
    } 
    for(int i = 0; i < len - 1; i++) { 
      nodes[i].next = nodes[i+1]; 
    } 
    /* try { 
      Thread.sleep(120000); 
    } catch (InterruptedException e) { 
      e.printStackTrace(); 
    }*/ 
    Node r1 = Node.loopReverse(nodes[0]); 
    r1.show(); 
    Node r = Node.recursionReverse(r1); 
    r.show(); 
 
  }  
} 

總結

對于遞歸和循環(huán),推薦使用循環(huán)實現(xiàn),遞歸在單鏈表過大時,會出現(xiàn)StatckOverflowError,遞歸涉及到方法的調用,在性能上也弱于循環(huán)的實現(xiàn)

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關文章

最新評論