链接列表以排序格式插入

时间:2013-11-03 03:49:34

标签: java linked-list

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的任何节点都没有被添加。请用简单的术语解释谢谢。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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;
            }
        }

答案 2 :(得分: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;
    }
}

}