2015-07-13 47 views
0

编辑: 对不起,这里是我调用insert()方法的代码。现在无限循环消失了,但插入(else ...)中的最后一种情况仍然不会按顺序添加字符串。按字母顺序排列的字符串插入Java链接列表

public static void main(String[] args) 
    { 
     Frequency f = new Frequency(); 
     String s1 = "apple"; 
     String s2 = "crayon"; 
     String s3 = "bear"; 
     String s4 = "apple"; 
     String s5 = ""; 
     f.insert(s1); 
     f.insert(s2); 
     f.insert(s3); 
     f.insert(s4); 
     f.insert(s5); 
     f.print(); 
    } 

输出测试: (苹果,2)(蜡笔,1)


我收到了我的大学课程的一个项目,需要我插入字符串到按字母顺序的链接列表。我想我有正确的方法,但运行该程序会导致无限循环;我不知道为什么。这里是我到目前为止的代码,我宁愿一个解释过的代码:

/* 
* Inserts a word into the linked list. If the word exists, increment the 
* count by q. 
*/ 
public void insert(E word){ 
    //word is empty 
    if(word.equals("")){ 
     return; 
    } 
    //list is empty 
    else if(isEmpty()) 
    { 
     Node n = new Node(word); 
     first = n; 
     N++; 
    } 
    //list already has word 
    else if(contains(word)) 
    { 
     Node cur = first; 
     while(cur != null) 
     { 
      if(cur.key == word) 
       cur.count++; 
      cur = cur.next; 
     } 
    } 
    //list only has 1 object 
    else if(N == 1) 
    { 
     Node n = new Node(word); 
     first.next = n; 
     N++; 
    } 
    //inserting new object 
    else 
    { 
     Node n = new Node(word); 
     Node cur = first; 
     while(cur != null) 
     { 
      if(cur.next != null) 
      { 
       if(cur.next.key.compareTo(word) <= 0) 
       { 
        Node temp = cur.next; 
        cur.next = n; 
        n.next = cur.next; 
        return; //exit, since the word has been added 
       } 
       cur = cur.next; 
      } 
      else 
       cur.next = n; 
     } 
     N++; 
    } 
} 
+1

您实际上正在调用'insert()'的代码在哪里? –

+0

分享你的代码插入方法...... – CoderNeji

+0

'== word'应该是一个'equals'或'的compareTo == 0'。 –

回答

0

当我看到你想你可以使用一个

TreeMap<String,Integer> 
按键的数量,正确的顺序所有按键

与你的目的和插入方式:

treeMap.put(key, treeMap.getOrDefault(key, 0)); 

你的问题: 如果你在你的问题的最后案“CUR”永远不能为null。 因为只有当cur.next!= null时才改变cur变量。所以一旦cur.next为空,你预计下一轮之后这个时间会中断。但是你不会改变cur的值。

while(cur != null) 
    { 
     if(cur.next != null) 
     { 
      if(cur.next.key.compareTo(word) <= 0) 
      { 
       Node temp = cur.next; 
       cur.next = n; 
       n.next = cur.next; 
       return; //exit, since the word has been added 
      } 
      ---> old position of cur = cur.next; 
     } 
     else { 
      cur.next = n; 
     } 
     cur = cur.next; ---> move it here 
    } 
+0

谢谢,这摆脱了无限循环,但我想知道如果我正确使用compareTo,因为那部分似乎仍然工作仍然 – drdevice