如何对此圈子列表进行排序?

时间:2014-11-05 05:39:20

标签: java sorting

我正在试图弄清楚如何制作一个有序的Circle List类。我有一个未排序的类,但我似乎有问题排序列表。我已经尝试在我在其他程序中使用的排序列表类的帮助下搞清楚它。我认为我需要使用compareTo()方法,但我似乎无法弄清楚如何做到这一点。

public class CRefUnsortedList<T extends Comparable<T>> implements ListInterface<T>
{
    protected int numElements;
    protected LLNode<T> currentPos;
    protected boolean found;
    protected LLNode<T> location;
    protected LLNode<T> previous;

    protected LLNode<T> list;

    public CRefUnsortedList()
    {
        numElements = 0;
        list = null;
        currentPos = null;
    }

    public void reset()
    {
        if (list != null)
        {
            currentPos = list.getLink();
        }
    }

    public T getNext()
    {
        T next = currentPos.getInfo();
        currentPos = currentPos.getLink();
        return next;
    }

    public String toString()
    {
        String listString = "List:\n";
        if(list != null)
        {
            LLNode<T> prevNode = list;
            do
            {
                listString = listString + " " + prevNode.getLink().getInfo() + "\n";
                prevNode = prevNode.getLink();
            }while(prevNode != list);
        }
        return listString;
    }

    protected void find(T target)
    {
        location = list;
        found = false;

        if(list != null)
        {
            do
            {
                previous = location;
                location = location.getLink();

                if(location.getInfo().equals(target))
                {
                    found = true;
                }
            }while((location != list) && !found);
        }
    }

    public boolean remove (T element)
    {
        find(element);
        if(found)
        {
            if(list == list.getLink())
            {
                list = null;
            }
            else
            {
                if (previous.getLink() == list)
                {
                    list = previous;
                }
                else
                {
                    previous.setLink(location.getLink());
                }
                numElements--;
            }
        }
        return found;
    }

    public T get(T element)
    {
        find(element);
        if (found)
        {
            return location.getInfo();
        }
        else
        {
            return null;
        }
    }

    public void add(T element)
    {
        LLNode<T> newNode = new LLNode<T>(element);
        if(list == null)
        {
            list = newNode;
            newNode.setLink(list);
        }
        else
        {
            newNode.setLink(list.getLink());
            list.setLink(newNode);
            list = newNode;
        }
        numElements++;
    }

    public int size()
    {
        return numElements;
    }

    public boolean contains(T element)
    {
        find(element);
        return found;
    }
}

0 个答案:

没有答案