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

}

これは、最初または頭よりも小さいすべてのデータ値に対して正常に機能します。より大きいものはリストに追加されません。たとえば、私のメイン メソッド Node root = new Node(200,null) では、200 を超えるノードで作成したノードは追加されません。簡単な言葉で説明してください。

4

3 に答える 3

0

コードの問題は、挿入の呼び出し方法に依存することです。コードで挿入を呼び出す方法がわかりません。以下のコードは、リストが降順でソートされていれば問題なく動作します。

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

}
于 2013-11-03T05:57:28.563 に答える
0

head.data が value より小さい場合は挿入しません。value が head.data より小さい場合は挿入します。

于 2013-11-03T04:06:40.247 に答える