【问题标题】:InsertionSort on Linked List , with Data from text file. Java链接列表上的 InsertionSort ,带有来自文本文件的数据。爪哇
【发布时间】:2017-06-04 00:20:28
【问题描述】:

我正在使用我的链接列表进行插入排序,但遇到了一个问题。

我的数据文件:

Myjob 66
Junk   17
Fun    25
Vital       99
Important   96
MoreFun    28
Work      69
Assignment  44

这是我的插入排序代码

public Node insertSort(Node node){
   Node sortedNode = null;
   while(node != null){
    Node current = node;
    node = node.next;
    Node x;
    Node previous = null;
    for(x = sortedNode; x != null; x = x.next){
        if(current.getData().getNum() > x.getData().getNum()){
                break;
         }
         previous = x;
    }
    if(previous == null){               
          current.next = sortedNode;
          sortedNode = current;
    }
    else{               
       current.next = previous.next;
       previous.next = current;
    }
  }
   sortedNode=head;
  return sortedNode; }

我目前的输出:

Name = Myjob            Priority=66
Name = Assignment            Priority=44
Name = MoreFun            Priority=28
Name = Fun            Priority=25
Name = Junk            Priority=17
null

他们跳过大于 66 的任何内容。有没有人知道如何解决这个问题,所以它可以从 99 显示到 17?我尝试重新排列文本文件中的顺序,最高的在前。那么程序就可以完美的进行从99到17的排序了。但是使用原始顺序,我的程序只能执行从 66 到最低的排序。我不知道为什么,以及如何解决?请帮忙。我对 Java 很陌生。非常感谢。

我的数据类

public class Data {

private String name;
private int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name=name;
}

public int getNum(){
    return num;
}

public void setNume(int num){
    this.num=num;
}

public String toString()
{
    return "Name = " + name + "            Priority=" + num ;
}

}

这是我的 LinkedList 类:

public class LinkedList {
Node head;
Node prev;
Node cur;


public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

public void printLinkedList(){
    System.out.println(head);
}

public void initializeLL(){
    Node currentNode = head;
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            if(currentNode == null){
                currentNode = n;
                head = n;
            }else{
                currentNode.setNext(n);
                currentNode = n;
            }
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        l1.initializeLL();
        l1.insertSort(l1.head); 
        l1.printLinkedList();
        System.out.println("************");
}
}

这是我的节点类:

public class Node{
Data dt;
Node next;

public Node(){

}
public Node(Data dt){
    this.dt=dt;
}


public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}


public Data getData(){
    return dt;
}

public void setData(Data dt){
    this.dt=dt;
}


public String toString()
{
    StringBuilder sb = new StringBuilder();
    sb.append(dt).append(System.getProperty("line.separator")); 
    sb.append(next).append(System.getProperty("line.separator")); 

    return sb.toString();

}
}

insertionSort 方法在 LinkedList 类中。

【问题讨论】:

  • 当您需要将项目添加到列表的开头时,您的问题似乎发生了。
  • 我也找到了。但我不知道如何修复我的代码。你能帮我吗?
  • @nhouser9 我刚刚添加了其余的代码。请看一下并提供帮助。非常感谢。
  • 您希望插入排序做什么?对整个列表进行排序?当我想到插入排序时,我想到的是在插入每个项目时对其进行排序,这不是这里发生的事情,因为您从文件初始化列表然后对其进行排序。
  • @nhouser9 那么我该如何修复我的代码呢?我卡住了。我是java新手。所以我对这些排序没有太多经验。可以给我看看吗?

标签: java sorting linked-list


【解决方案1】:

这里发生了几件事。首先,您的代码中有一些错误,例如返回尚未更新的head。这可以通过在列表中途开始迭代来轻松解释您所看到的行为。

更重要的是,这对我来说似乎不是插入排序的实现。插入排序是通过在正确的点插入已经排序的列表来完成的。所以看起来像:

sortedList Sort(unsortedlist):
   sortedList = []
   foreach item in unsortedlist:
     sortedList.InsertAtTheRighPlace(item)
   return sortedList

【讨论】:

  • 非常感谢您的指导,兄弟。
【解决方案2】:

你确定你的代码是正确的吗? 我跟踪您的代码,发现 for 循环无论如何都没有运行,因为 x 在每次运行 insertSort() 函数时始终为空。

如何调用 insertSort() 函数对数据进行排序?

编辑

好的。我查看了您的代码。我发现你的排序是正确的,但是排序后 LinkList 的函数头没有更新。因此,您的代码从旧头打印排序列表。 您应该在排序功能后更新链表的头部。

【讨论】:

  • 你确定你的代码是正确的吗?实际上他不是,加上你作为答案的回答是疑问的,而不是基于解决方案的,尝试提出解决方案是我的意思是
  • @hadi.mansouri 我刚刚在上面添加了我的其余代码。请看一下并提供帮助。非常感谢。
  • @ShayHaned 我刚刚添加了我的代码。请看看和帮助。非常感谢。
  • 这不是答案,应该是评论。
  • @nhouser9 我无权发表评论。我没有足够的声誉发表评论。 StackOverflow 不允许我发表评论。 :(
【解决方案3】:

好的,所以下面的代码片段这是我的插入排序代码正在做一些严肃的解决方法,我想即使你也无法正确想象:)。

尝试将您的问题分解为更简单的步骤,您将如何实现一个 LinkedList,您可以在其中以升序或降序形式添加一个整数(真的,只是 OOP 复杂性不同)。我刚刚测试过的以下代码将帮助您至少了解您应该如何实现一个通过 InsertionSort algo 增长的 LinkedList,请注意这是处理 升序案例

public class LinkedList
{

    public Node first , last;

    public class Node
    {
        public int data;

        public Node next;

        public Node( int data )
        {
            this.data = data;
        }
    }

    public void addInsertSort( int num )
    {
        if( isEmpty() )
        {
            first = new Node( num );
            last = first;
        }
        else
        {
            Node newNode = new Node( num );
            Node curNode = first , preNode = null;
            while( curNode != null && newNode.data > curNode.data )
            {
                preNode = curNode;
                curNode = curNode.next;
            }
            if( curNode == first )
            {
                newNode.next = first;
                first = newNode;
            }
            else
            {
                if( curNode != null && preNode != null ) //middle of list
                {
                    newNode.next = curNode;
                    preNode.next = newNode;
                }
                else if( curNode == null ) // end of list
                {
                    preNode.next = newNode;
                    last = newNode; 
                }
            }
        }
    }

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

    public String toString()
    {
        String str = "[";
        for( Node curNode = first; curNode != null; curNode = curNode.next )
        {
            str += curNode.data + " ";
        }
        return str + "]";
    }

    public static void main( String[] args )
    {
        LinkedList list = new LinkedList();

        list.addInsertSort( 4 );
        list.addInsertSort( 5 );
        list.addInsertSort( 1 );
        list.addInsertSort( 6 );
        list.addInsertSort( 10 );
        list.addInsertSort( 0 );

        System.out.println( list );
    }

}

对不起,这里的代码编辑器真的要杀了我,请不要介意频繁的重新编辑

现在继续讨论如何将这个想法整合到你的方法中,你可以解决这样的问题,并确保它看起来完全像这样

// You really dont need more variables in your LinkedList class
// Both of these are enough, forget currentNode reference
public Node head , last;

public void initializeLL(){
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            addInsertSort( n );
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}


public Node addInsertSort( Node newNode )
{
    if( isEmpty() )
    {
        head = newNode;
        last = head;
    }
    else
    {
        Node curNode = head , preNode = null;
        // This is How InsertionSort would have gone to search the list
        while( curNode != null && newNode.getData().getNum() > curNode.getData().getNum() )
        {
            preNode = curNode;
            curNode = curNode.next;
        }
        //Thats the happy ending of the insertionSort algo
        //Now we need to link newNode with OUR DYNAMICALLY GROWING LIST
        //When the insertion Algo stopped, It told us where the newNode 
        //shall be placed in comparison to the current state of list

        // Is this supposed to be the head node now??
        if( curNode == head )
        {
            newNode.next = head;
            head = newNode;
        }
        else // maybe we landed BETWEEN the list or at the END OF LIST??
        {
            if( curNode != null && preNode != null ) //BETWEEN THE list
            {
                newNode.next = curNode;
                preNode.next = newNode;
            }
            else if( curNode == null ) // end of list
            {
                preNode.next = newNode;
                last = newNode; 
            }
        }
    }
    return newNode; 
}

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

如果还有问题请告诉我,我会更深入地解释

【讨论】:

  • 太棒了。我的程序运行良好。非常感谢。
  • 非常感谢,兄弟。我的程序现在运行良好。
猜你喜欢
  • 1970-01-01
  • 2019-07-19
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多