链表上的冒泡排序实现

时间:2013-04-17 15:21:25

标签: java linked-list bubble-sort

我在LinkList.java中遇到错误,在“curr.names.length() - 1”中。 .length是一个错误。我该如何解决?这里仍然是新的,我并不太了解Java。只是想我会试一试。这是我得到的代码:

SinglyNode.java

public class SinglyNode
{
public Object names;
public SinglyNode next;

public SinglyNode (Object name1)
{
    names = name1;
    next = null;
}

public void setNext(SinglyNode next1)
{
    next = next1;
}

Object getObject()
{
    return names;
}

SinglyNode getNext()
{
    return next;
}

void displayLink()
{
    System.out.print("{" + names + "}");
}
}

LinkList.java 错误在这里

public class LinkList
{
SinglyNode first;
SinglyNode last;

public boolean isEmpty()
{
    return (first == null);
}

void insertFirst(Object name1)
{
    SinglyNode newNode1 = new SinglyNode(name1);
    newNode1.next = first;
    first = newNode1;
}

void display()
{
    SinglyNode current = first;
    while(current != null)
    {
        current.displayLink(); // print data
        current = current.next; // move to next link
    }
    System.out.println("\n");
}

public void bubbleSort()
{
    int length = 0;
    SinglyNode hold = first;
    while(true)
    {
        if(hold == last)
        {
            break;
        }
        hold = hold.next;
        length++;
    }
    while(true)
    {
        if(length == 0)
        {
            break;
        }
        int i = 0;

        SinglyNode curr = first;
        while(true)
        {
            if(i == length)
            {
                break;
            }
            if( curr.names.charAt(curr.names.length()-1) > 
                    curr.next.names.charAt(curr.next.names.length()-1))
            {
                swap(curr);
            }
            curr = curr.next;
            i++;
        }
        length--;
    }
}

private void swap(SinglyNode node)
{
    Object temp = node.names;
    node.names = node.next.names;
    node.next.names = temp;
}
}

这是主要课程 MainApp.java

ppublic class MainApp
{
public static void main (String args[])
{
    LinkList list = new LinkList();

    list.insertFirst("Squirtle");
    list.insertFirst("Bulbasaur");
    list.insertFirst("Charmander");
    list.insertFirst("Pichu");
    list.insertFirst("Ghastly");
    list.insertFirst("Mewtwo");
    list.insertFirst("Dialga"); 

    System.out.println("LIST: ");
    list.display();

    System.out.println("BUBBLE SORT: ");
    list.bubbleSort();
    list.display();

}
}

1 个答案:

答案 0 :(得分:0)

Object没有length()方法 - 您只能使用相应的方法签名在类上调用.length()。你有意这是String吗?如果是,请将您的代码更改为public String namespublic SinglyNode(String name1)String getObject()(或String getName()String getString()