简体   繁体   English

需要帮助在已排序的LinkedList中添加节点

[英]Need help adding a node in sorted LinkedList

I'm trying to add a new Customer object (which should be node.data, not node) in sorted order by the customer object's name alphabetically. 我试图按客户对象名称的字母顺序按顺序添加新的客户对象(应为node.data,而不是节点)。 But it's not working. 但这不起作用。 It's printing out the list in unsorted order (unchanged from original order). 它以未排序的顺序打印出列表(与原始顺序保持不变)。

public void  add(Customer newNode, int dummy){
   if (head == null){ // The first node
      head = tail = this;
      head.setData(newNode);
      size=1;
      return;

   }else{
       CustomerList last = null;
       for(CustomerList node = head; 
               node != null && node.getData().toString().compareTo(newNode.name) < 0; 
                    node = node.next){
          last = node; 

       }
       CustomerList newList = new CustomerList(newNode);
       newList.setNext(last.next);
       last.next = newList;
   }

} // add

Input of Customer objects from txt file. 输入txt文件中的Customer对象。 Should print out again but in alphabetical order (customer name). 应重新打印,但应按字母顺序(客户名称)打印。

10121,Airgo Fresh ods,OH,870023
10125,Bird Out fittered ,MI,870023
10134,Kit river ,IL,870023
10167,Mouin Gontaods,OR,870021
10178,Theiasu El senter,CA,870022

Code which reads data from txt file and creates objects and adds to list: 从txt文件读取数据并创建对象并添加到列表的代码:

public void byCustomerName()
 {
 records = null;
 System.gc();
 CustomerList.setHead(null);
 records = new CustomerList();
 try
  {
  String line;
  StringTokenizer st;
  String id, name, state, salesrep;
  BufferedReader infile = new BufferedReader(new FileReader("Customer.txt"));
  while ((line = infile.readLine()) != null)
      {
      st = new StringTokenizer(line, ",");
      id = st.nextToken(",");
      name = st.nextToken(",");
      state = st.nextToken(",");
      salesrep = st.nextToken(",");
      records.add(new Customer(id, name, state, salesrep), 99);
      }
  infile.close();
  } catch (IOException x) { System.err.println(x); } 
 } // byCustomerName

I think your code has all sorts of problems in it. 我认为您的代码中存在各种问题。 For one, I don't ever see you updating head or tail if you replace the first or last element. 例如,如果您替换第一个或最后一个元素,我再也看不到您更新了headtail Also, there is no check for last potentially being null . 同样,不检查last可能为null It'll be hard to say more without knowing how some of your underlying CustomerList items work. 不知道您的某些底层CustomerList项目是如何工作的,很难说更多。

I actually did this same exact assignment two semesters ago but decided to take the class again because I was unable to take the final. 实际上,我在两个学期前做了同样的作业,但由于无法参加决赛而决定再次上课。 But since no programming for two semesters, I'm now extremely rusty. 但是由于两个学期都没有编程,所以我现在非常生锈。 I'm just going to give up for now and use my old solution that I came up for the first time I took the class. 我现在要放弃,并使用我第一次上课时提出的旧解决方案。

Solution: 解:

public void add(Customer newNode, int dummy) {  
    CustomerList before = null;
    boolean inserted = false;
    if (head == null) {  //first node   
        head = tail = this;
        head.setData(newNode);
        return;
    } else {
        CustomerList curr = head;
        while(curr != null) {
            String currentName = curr.getData().getName();
            String newNodeName = newNode.name;
            if (currentName.compareToIgnoreCase(newNodeName) > 0) {

                CustomerList cList = new CustomerList(newNode);
                cList.setNext(curr);//curr is greater than clist, therefore cList's next element is curr
                if(before!=null)
                    before.setNext(cList);
                else {  //this tests the case when 
                    //the newNode goes at the BEGINNING of the list
                    head = cList;
                }
                curr = cList;
                inserted = true;
                return;
            }
            before = curr;
            curr = curr.next;               
        }
    }
    if(!inserted) {
        add(newNode);
    }

} // add

As Sudhanshu already told you can use Collections.sort(-) method on your List object or as an alternate just use TreeSet in case if you want unique objects. 正如Sudhanshu已经告诉您的那样,您可以在List对象上使用Collections.sort(-)方法,或者作为替代,仅在需要唯一对象的情况下使用TreeSet Its better to utilize inbuilt methods of java API as these are less error prone and more reliable, at the same time you can reduce your code and time to mug up in it. 更好地利用java API内置方法,因为这些方法更不易出错,更可靠,同时您可以减少代码并减少使用它的时间。

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

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