LinkedList与Scanner的addSort方法

时间:2016-04-17 14:00:20

标签: java sorting linked-list

所以我有一个" ItemList"其中每个节点都包含一个名称和一个数字,我想创建一个addSort方法,按字母顺序添加到列表中。

我已经有两种方法:

我找到索引应该在哪里:

public int getIndexName(String id){
    Node temp = header;
    int count = 0;
    while(temp.next.itm.name.compareTo(id) < 0){
        temp = temp.next;
        count++;
    }

    return count;
}

和添加索引的那个:

public void add( Item newItem, int index)
  {
      if(index < 0 || index > size){
          throw new IndexOutOfBoundsException();
      }
    Node nynode = new Node(newItem);
    Node temp = header;
    //go to the index or the last element in list, whichever comes first.
    for(int i = 0; i< index && temp.next != null; i++){
        temp = temp.next;
    }
    // set the nynode's next-node reference to this node's next-node reference
    nynode.setNext(temp.next);
    //set this node's next-node reference to the new node
    temp.setNext(nynode);
    size++;

  }

现在正在处理我的addSort方法,如下所示:

public void addSort(Item newItem){
    if(size > 2){
        int index = this.getIndexName(newItem.name);
        this.add(newItem, index);
    }
    else{
        add(newItem);
    }
}

如果大小不大于2,则只需添加一个普通的add方法,因为我需要两个名称来比较。这适用于4个元素并且它被排序但是有更多元素我得到nullpointerexception。我会用扫描仪做更多元素,所以我需要帮助我做错了。

提前感谢!

0 个答案:

没有答案