简体   繁体   English

链接列表,从文本文件中读取,并按键排序

[英]Linked List, read from text file, and sort by key

I'm trying to sort the Linked List by the key( priority number, the int number) from highest to lowest, with the data from text file. 我试图按最高(到最低)的键(优先级编号,整数编号)和文本文件中的数据对链接列表进行排序。 I'm stucking at insert the item and sort them. 我坚持插入项目并对其进行排序。 Here is My text file. 这是我的文本文件。

Myjob 66 我的工作66

Junk 17 垃圾17

Fun 25 乐趣25

Important 96 重要96

Vital 99 至关重要的99

MoreFun 28 乐趣28

Work 69 工作69

Assignment 44 作业44

Here is my Linked List class 这是我的链表类

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;


@SuppressWarnings("unused")
public class LinkedList {
    Node head;
    Node prev;
    Node cur;
    Node node;

public LinkedList(){

}

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

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

//insert method
public void insert(Data dt){
    try {
        if(head==null){
            head = new Node(dt.getData(), null);
            System.out.println("Opps");
            }
        else if (dt.getData().num > head.dt.num){
            head = new Node(dt.getData(),head);
            System.out.println("Was Here");}
        else if (head.getNext()==null){
            head.setNext(new Node(dt.getData(),null));
            }
        else{
            cur = head.getNext();
            for(prev = head;cur!= null;cur=cur.getNext()){
                if(cur.dt.num>prev.dt.num){
                    Node temp = new Node(dt.getData(),cur);
                    prev.setNext(temp);
                    break;
                }
                else{
                    prev=cur;

                }
            }
        }
    }
        catch (NullPointerException e){
            System.out.println("Here is Error");
        }


}



//Running Linked list
public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        Data dt = new Data();

        l1.insert(dt);


}

} }

Here is My Node class: 这是我的节点类:

public class Node {
Data dt;
Node next;


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


public Node getNext(){
    return next;
}

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


public Data getData(){
    return dt.getData();
}




}

Here is my Data class: 这是我的数据类:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Data {

protected String name;
protected int num;

public Data(){
}

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

//getter to get Data
@SuppressWarnings("unused")
public Data getData(){
        try{
            int count =0;
            File x = new File("Asg2Data.txt");
            Scanner sc = new Scanner(x);
            while (sc.hasNext()){
                String name = sc.next();
                int num = sc.nextInt();
                Data data= new Data(name,num);
                System.out.println("Name = "+ name+"          "+"Priority = "+num);
                System.out.println(" ");
                count++;
            }
            System.out.println("Total Objects: "+count);
            sc.close();
        }catch(FileNotFoundException e){
            System.out.println("Error");
        }
        return this;
}

//Compare Function
//  public int compare(Data dt){
//      if (this.getData().num > dt.getData().num)
//          return 1;
//      else if (this.getData().num < dt.getData().num)
//          return -1;
//      else
//          return 0;
//  }


// Testing: Worked !!!!!    
    public static void main(String[] args){
        Data d1 = new Data();
        d1.getData();
    }

}

My currently output, when I run from Linked List class: 我从链接列表类运行时的当前输出:

Name = Myjob          Priority = 66

Name = Junk          Priority = 17

Name = Fun          Priority = 25

Name = Important          Priority = 96

Name = Vital          Priority = 99

Name = MoreFun          Priority = 28

Name = Work          Priority = 69

Name = Assignment          Priority = 44

Total Objects: 8
Opps

My insert method always stop at the first if statement, and never keep going. 我的insert方法总是在第一个if语句处停止,并且永远不会继续。 I have no clue how to fix it. 我不知道如何解决它。 At the mean time, it can not perform the insert the data + sort them by the priority number from highest to lowest. 同时,它无法执行插入数据+按优先级从高到低的顺序对其进行排序。 Can anyone help me ? 谁能帮我 ? I'm super new in Java. 我是Java的超级新手。 Thank you so much. 非常感谢。

-Dustin -Dustin

First things first your LinkedList is not getting initialized is because in your Data->getData() method you are creating the data objects but never assigning them to the head and the next of the LinkedList head. 首先,未初始化LinkedList的原因是因为在Data->getData()方法中,您正在创建数据对象,但从未将它们分配给LinkedList头和下一个头。

As you are new to Java just want to give you some tips on coding with Java. 当您刚接触Java时,只想给您一些使用Java编码的技巧。

  • Don't use suppress warnings unless utmost important. 除非非常重要,否则不要使用抑制警告。 Most of the time you can handle them. 大多数时候您可以处理它们。
  • Try to segregate the code as much as possible. 尝试尽可能分离代码。 This will help you and everybody else to understand the code. 这将帮助您和其他所有人理解代码。 Ex. 防爆。 why does your Data class have the initialization code, it should be in the LinkedList. 为什么您的Data类具有初始化代码,它应该在LinkedList中。 Data is just a representation class which will act as a model for your data (This may be design consideration and you might have your reasons to do this..just saying) 数据只是一个表示形式类,它将充当数据的模型(这可能是设计考虑因素,您可能有理由这样做。
  • You can also go through the identifiers once and how to use them. 您也可以浏览一次标识符以及如何使用它们。

I won't give you the complete the code (because then there will be nothing for you to do) but the below snippet should get you started. 我不会给您完整的代码(因为那样您将无事可做),但是下面的代码片段应该可以帮助您入门。 I have tried to use your code as much as possible so that it is easier for you to understand. 我试图尽可能多地使用您的代码,以便您更容易理解。 Below code will initialize a LinkedList with the data required, maybe you can take care from there. 下面的代码将使用所需的数据初始化LinkedList,也许您可​​以从那里开始。 You can continue to ask any questions if you face any issue going forward 如果您遇到任何问题,可以继续提出任何问题

` `

 import java.io.File;
 import java.util.Scanner;

 public class LinkedList
    {
        Node head;

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

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

        private 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.setNextNode(n);
                        currentNode = n;
                    }
                }
                sc.close();
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }

    }

    class Node
    {

        private Data data;

        private Node nextNode;

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

        public Data getData()
        {
            return data;
        }

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

        public Node getNextNode()
        {
            return nextNode;
        }

        public void setNextNode(Node nextNode)
        {
            this.nextNode = nextNode;
        }

        @Override
        public String toString()
        {
            return "Node [data=" + data + ", nextNode=" + nextNode + "]";
        }



    }

    class Data
    {

        private String name;

        private int data;

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

        public String getName()
        {
            return name;
        }

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

        public int getData()
        {
            return data;
        }

        public void setData(int data)
        {
            this.data = data;
        }

        @Override
        public String toString()
        {
            return "Data [name=" + name + ", data=" + data + "]";
        }
    }

` `

Your advices are so awesome. 您的建议真棒。 I just fix my code. 我只修复我的代码。 And it works well now. 而且现在效果很好。 for now I'm still stucking with the sorting part. 现在,我仍然停留在排序部分。 I'm doing insertionSort. 我在做insertSort。 and here is my code. 这是我的代码

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;
        }
      }
      return sortedNode; }

My output is 我的输出是

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

they skips whatever greater than 66. Do you have any ideas how to fix this issue, so it can dipslay from 99 down to 17? 他们会跳过大于66的值。您是否有解决此问题的想法,因此可以将其从99降低到17? I rearrange the order in the text file, with the highest first. 我以最高的顺序重新排列了文本文件中的顺序。 then It can perform sorting from 99 back to 17 perfectly. 那么它可以完美地执行从99到17的排序。 But with the original order, my program just perform sorting from 66 to lowest. 但是按照原始顺序,我的程序只执行从66到最低的排序。 I don't know why ,and how to fix it? 我不知道为什么,以及如何解决? Thank you so much. 非常感谢。

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

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