-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

如果 head.data 小于 value,则不想插入,如果 value 小于 head.data,则要插入。

于 2013-11-03T04:06:40.247 回答
0

if (head == null || head.data <= value) 当您将 200 插入头部时,您的问题就在这里。任何大于 200 的都不会被添加。因为你做了head.data <= value。你把 200 添加到 head 中,然后 headNULL不再存在,所以你的程序将检查是否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;
            }
        }
于 2013-11-03T04:19:36.443 回答
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 回答