2013-11-03 37 views
-1
package practise; 
public class Node 
{ 
    public int data; 
    public Node next; 

    public Node (int data, Node next) 
    { 
     this.data = data; 
     this.next = next; 
    } 

    public int size (Node list) 
    { 
     int count = 0; 
     while(list != null){ 
      list = list.next; 
      count++; 
     } 
     return count; 
    } 

    public static Node insert(Node head, int value) 
    { 
     Node T; 
     if (head == null || head.data <= value) 
     { 
      T = new Node(value,head); 
      return T; 
     } 
     else 
     { 
      head.next = insert(head.next, value); 
      return head; 
     } 
    } 

} 

這項工作適用於所有數據值小於第一個或頭部。大於的任何內容都不會被添加到列表中。因此,例如在我的主要方法節點根=新節點(200,空)我現在創建的任何節點超過200不會被添加。請簡單說明謝謝。以排序格式插入鏈接列表

回答

0

你的代碼的問題是,它取決於如何調用插入。我不知道你是如何在代碼中調用insert的。下面的代碼將做工精細,用列表排序降序排列:

public class SortedLinkedList { 
public static void main(String[] a) { 
    Node head = Node.insert(null, 123); 
    head = Node.insert(head, 13); 
    head = Node.insert(head, 3123); 
    head = Node.insert(head, 3); 
    head = Node.insert(head, 87); 
    head = Node.insert(head, 56); 
    head = Node.insert(head, 2332); 
    head = Node.insert(head, 5187); 
    do { 
     System.out.print(head.data + ", "); 
     head = head.next; 
    } while (head != null); 
    } 
} 

class Node { 
public int data; 
public Node next; 

public Node(int data, Node next) { 
    this.data = data; 
    this.next = next; 
} 

public int size(Node list) { 
    int count = 0; 
    while (list != null) { 
     list = list.next; 
     count++; 
    } 
    return count; 
} 

public static Node insert(Node head, int value) { 
    Node T; 
    if (head == null || head.data <= value) { 
     T = new Node(value, head); 
     return T; 
    } else { 
     head.next = insert(head.next, value); 
     return head; 
    } 
} 

} 
+0

嘿感謝它解決它的問題是他們的方式,我稱它在我的主要方法,我doiing節點頭=新節點(200,空);然後我繼續做這個head.insert();它應該像這樣head = head.insert();但是請你解釋一下這兩個陳述有什麼不同,請再次感謝。 (就像在如果我知道即時通訊返回的T是頭,但在其他我回來的頭不head.next我困惑那裏如何道理是有道理的):D – natgeo201

+0

您的方法插入()總是返回頭的引用列表的節點。你只需要每次分配返回值來跟蹤它。順便說一句,這不是一個好的編程方式。試試它的方式,你的調用代碼只是將值傳遞給鏈表對象.... –

0

如果head.data小於值,您不想插入,如果值小於head.data,則要插入。

0

if (head == null || head.data <= value) 你的問題在這裏,當你插入200的頭部。大於200的任何內容都不會被添加。因爲你做了head.data <= value。你把200加到頭上,那麼頭不再是NULL了,那麼你的程序會檢查是否head.data <= value,如果是的話,把它加到列表中。否則不要。

public static Node insert(Node head, int value) 
     { 
      Node T; 
      if (head == null || head.data >= value) 
      { 
       T = new Node(value,head); 
       return T; 
      } 
      else 
      { 
       head.next = insert(head.next, value); 
       return head; 
      } 
     }