我创建了基于LinkedList的集合,并且想要对节点进行排序,我可以为集合添加值,我可以在没有任何标准Java库的情况下这样做吗? 包ru.matevosyan;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* DynamicSetByLinkedListclass.
*创建于2017年5月29日。 * @author Matevosyan Vardan * @version 1.0 * /
public class DynamicSetByLinkedList<E> implements IDynamicSetByLinkedList<E>, Iterable<E> {
private Node<E> last;
private int size = 0;
private Node<E> first;
/**
* Constructor.
*/
public DynamicSetByLinkedList() {
}
/**
* Create to add value to the set.
* @param value is value that type which you declare in generics.
*/
@Override
public void add(E value) {
if (!checkDuplicate(value)) {
linkLast(value);
}
}
private boolean checkDuplicate(E value) {
Node<E> firstNode = first;
boolean hasDuplicate = false;
for (int i = 0; i < size & size > 1; i++) {
firstNode = firstNode.next;
if (firstNode == null) {
break;
}
if (firstNode.item.equals(value)) {
hasDuplicate = true;
}
}
return hasDuplicate;
}
/**
* linkLast assign LinkedList Node to the last Node in the list and if it is the first value assign as first too.
* @param elementValue is value.
*/
private void linkLast(E elementValue) {
Node<E> lastNode = last;
Node<E> newNode = new Node<>(lastNode, elementValue, null);
last = newNode;
if (lastNode != null) {
lastNode.next = newNode;
} else {
first = newNode;
}
size++;
if(size > 1) {
sortByHashcode();
}
}
private void sortByHashcode() {
**here going to be a sort algorithm**
}
}
/**
* For returning the size of set.
* @return size
*/
public int len() {
return size;
}
/**
* Class Node describe linkedList entry.
* @param <E> parameter that defined when create an instance of a class.
*/
private static class Node<E> {
E item;
Node<E> prev;
Node<E> next;
Node(Node<E> prev, E element, Node<E> next) {
this.prev = prev;
this.item = element;
this.next = next;
}
}
/**
* Override iterator method from interface Iterable.
* @return an instance of Iterator type.
*/
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
int count = 0;
@Override
public boolean hasNext() {
return (count < size) && (last != null);
}
@Override
public E next() {
count++;
Node<E> nextNode = first;
if (nextNode != null && count > 1) {
nextNode = nextNode.next;
}
if (nextNode == null | size < count) {
throw new NoSuchElementException("Does not exist");
}
return nextNode.item;
}
};
}
}
答案 0 :(得分:0)
如果链接列表包含基本类型,您可以使用:
进行排序Collections.sort(list,null);
如果链表包含您创建的类的对象,那么您应该实现Comporator来执行您自己的比较逻辑
答案 1 :(得分:0)
由于您的集合将在每个add()
方法之后进行排序,因此您需要在列表中找到新元素的位置。看,当你添加第一个元素时,你的集合肯定是有序的,所以添加你需要的下一个元素来找到它们的特定位置。所以你可以使用下一个实现:
private void sortByHashcode() {
Node<E> node = first;
while (node != null) {
if (last.item.hashCode() < node.item.hashCode()) {
Node<E> tmp = last.prev;
last.next = node;
last.prev = node.prev;
node.prev = last;
if (last.prev == null) {
first = last;
} else {
last.prev.next = last;
}
tmp.next = null;
last = tmp;
break;
}
node = node.next;
}
}
P.S。但是,在我看来,这是一个非常奇怪的收藏。我想你应该再考虑一下,你可以使用一个标准的Java集合(即TreeSet和你的比较器)。你能解释一下你想解决的问题吗?