前面实现了双向链表:https://www.cnblogs.com/wwjj4811/p/15108917.html
可排序也简单,直接继承DoublyLinkedList
/**
* 可排序的双向链表
* @author wen.jie
* @date 2021/8/9 21:31
*/
public class SortedDoublyLinkedList<T extends Comparable<T>> extends DoublyLinkedList<T>{
@Override
public void add(T t){
if (isEmpty()){
Node<T> node = new Node<>(t, head, null);
head.next = node;
last = node;
}else {
sort(t, head.next);
}
size++;
}
private void sort(T t, Node<T> node) {
if(node.next == null){
if(node.item.compareTo(t) < 0)
putLast(t);
else
insert(t, last.pre, last);
}else {
if(node.item.compareTo(t) < 0)
sort(t, node.next);
else
insert(t, node.pre, node);
}
}
}
测试:
SortedDoublyLinkedList<Integer> list = new SortedDoublyLinkedList<>();
list.add(1);
list.add(1);
list.add(3);
list.add(2);
list.add(1);
list.add(2);
list.add(5);
list.add(4);
for (Integer integer : list) {
System.out.println(integer);
}