简体   繁体   English

按顺序将项目插入自定义链表

[英]Insert items into Custom LinkedList in Order

I'm trying to insert items into a custom linked list, while keeping the list in order.我正在尝试将项目插入自定义链接列表,同时保持列表有序。

My work up to now is this:我到现在的工作是这样的:

public class CustomList {   

    public CustomList() {
        this.first = null;
    }
    public void insert(Comparable newThing) {
        Node point = this.first;
        Node follow = null;
        while (point != null && point.data.compareTo(newThing) < 0) {
            follow = point;
            point = point.next;
        }
        if (point == null) {
            Node newNode = new Node(newThing);
            newNode.next = this.first;
            this.first = newNode;
        } else {
            Node newNode = new Node(newThing);
            newNode.next = point;
            if (follow == null) {
                this.first = newNode;
            } else {
                follow.next = newNode;
            }
        }
    }
    private Node first;

    private class Node {

        public Comparable data;
        public Node next;

        public Node(Comparable item) {
            this.data = item;
            this.next = null;
        }
    }
}

The output I get from this looks like it orders parts of the list, then starts over.我从中得到的 output 看起来像是订购了列表的一部分,然后重新开始。

Example (I'm sorting strings):示例(我正在对字符串进行排序):

Instead of getting something like a,b,c,...,z而不是得到像a,b,c,...,z这样的东西

I get a,b,c,...,z,a,b,c,...,z,a,b,c,...,z我得到a,b,c,...,z,a,b,c,...,z,a,b,c,...,z

So it looks like it doesn't "see" the whole list at certain points.所以看起来它在某些点上没有“看到”整个列表。

This is part of a HW assignment, so I'd appreciate suggestions, but let me try to figure it out myself!这是硬件任务的一部分,所以我很感激建议,但让我自己试着弄清楚!

What happens if you insert an element which is greater than all your existing elements?如果您插入一个大于所有现有元素的元素会发生什么?

You want to insert the element at the end, but in fact you are inserting it at start.您想在末尾插入元素,但实际上您是在开头插入它。 And any later elements will then inserted before this (if they are smaller), or again at start.然后任何后面的元素都将在此之前插入(如果它们更小),或者在开始时再次插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM