链表java中的选择排序

时间:2016-01-28 18:18:57

标签: java sorting linked-list selection-sort

我的程序没有对列表进行排序,我无法弄清楚问题。 排序前和排序后列表相同。

 public void SelectionSort(){
    for (Node index = head; ((index != null)&&(index.getnext()!=null)); index = index.getnext()) {
          Node min = index;
          for (Node test = min.getnext(); test != null; test = test.getnext()) {
            if (test.getAcc().compareTo(min.getAcc()) < 0){
                min = test; 
            } 
          }
          if(index!=min){
              Node temp = new Node();
              temp=index;
              index=min;
              min =temp;
          }  
    }
}

以下是我的班级节点:

public class Node {
    private int ID;
    private String Acc;
    private String Symbol;
    private String Function;
    private String UniGene;
    private String Chromosome;
    private Node next;

    public Node(){

    }
    public Node(int id, String acc,String unigene, String symbol, String chromosome, String function){
        ID=id;
        Acc=acc;
        Symbol=symbol;
        UniGene = unigene;
        Chromosome = chromosome;
        Function=function;
    }
    public void displayNode() // display 
    {
        System.out.print("{"+ID+","+Acc+","+Symbol+","+Function+"} \n");
    }
    int getID(){
        return ID;
    }
    String getAcc(){
        return Acc;
    }
    String getUniGene(){
        return UniGene;
    }
    String getSymbol(){
        return Symbol;
    }
    String getChromosome(){
        return Chromosome;
    }
    String getFunction(){
        return Function;
    }
    void setnext(Node newnode)
    {
        next = newnode;
    }
    Node getnext()
    {
        return next;
    }
}

1 个答案:

答案 0 :(得分:0)

我认为问题在于移动节点时需要注意next指针。在原始代码中,您只需交换2个引用,但不更改列表中的顺序:

          Node next = min.getnext();
          min.setnext(index);
          index.setnext(next);

这不会直接起作用,但问题在于此。您需要保存“previous”节点,并设置previous.setnext(index)或类似的东西。

顺便说一句:

 Node temp = new Node();
 temp=index;

您创建一个新节点,但不使用它,因为在下一行中您将索引指定给temp。

Node temp = index;
相关问题