我如何使我的自定义通用类型链接列表在Java排序? [英] How would I make my custom generic type linked list in Java sorted?

查看:175
本文介绍了我如何使我的自定义通用类型链接列表在Java排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中编写我自己的链接列表,属于通用类型,而不是使用java集合链接列表。链接列表的add方法由以下代码组成:

I am writing my own linked list in java that is of generic type instead of using the java collections linked list. The add method for the linked list is made up of the following code:

public void add(T item, int position) {
  Node<T> addThis = new Node<T>(item);
  Node<T> prev = head;
  int i;

  if(position <= 0) {
    System.out.println("Error: Cannot add element before position 1.");
  }

  else if(position == 1) {
    addThis.setNext(head);
    head = addThis;
  } else {
    for(i = 1; i < position-1; i++) {
      prev = prev.getNext();
      if(prev == null) {
        System.out.println("Cannot add beyond end of list");
      }
    } // end for
    addThis.setNext(prev.getNext());
    prev.setNext(addThis);
  }
} // end add

当我添加一个新项目时,该项目与另一个项目进行比较,并按字母顺序插入?我已经调查了使用compareTo,但我不知道如何做。

How would I make it so that when I add a new item, the item is compared to another item and is inserted alphabetically? I have looked into using compareTo but I cannot figure out how to do it.

感谢

b $ b我有各种类:我有一个类叫做 Dvd ,它有一个标题(字符串)的方法和变量,和该标题的拷贝数(int)。我还有链接列表类 listinterface 节点类主类

I have various classes: I have a class called Dvd which has methods and variables for a title(string) and number of copies of that title(int). I also have a linked list class, a listinterface, a node class, and a main class.

推荐答案

我终于搞清楚了通过使用插入排序:

I finally figured it out by using an insertion sort:

public void add(Dvd item) {
  DvdNode addThis = new DvdNode(item);
  if(head == null) {
    head = addThis;
  } else if(item.getTitle().compareToIgnoreCase(head.getItem().getTitle()) < 0) {
      addThis.setNext(head);
      head = addThis;
    } else {
        DvdNode temp;
        DvdNode prev;
        temp = head.getNext();
        prev = head;
        while(prev.getNext() != null && item.getTitle().compareToIgnoreCase
            (prev.getNext().getItem().getTitle()) > 0) {
          prev = temp;
          temp = temp.getNext();
        }
        addThis.setNext(temp);
        prev.setNext(addThis);
      }
}

这篇关于我如何使我的自定义通用类型链接列表在Java排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆