有序链表--Java实现

 /*有序链表--使用的是单链表实现
*在插入的时候保持按照值顺序排列
*对于删除最小值的节点效率最高--适合频繁的删除最小的节点
* */
public class MySortedLinkList {
public Link first; public MySortedLinkList() {
first = null;
} public boolean isEmpty(){
return first == null;
} public void insert(int key){
Link newLink = new Link(key);
Link previous = null;
Link current = first;
while(current != null && key > current.id){ //找下个节点
previous = current;
current = current.next;
}
//比当前节点值小,刚好插入当前节点前面
if(previous == null){//链表是空的
first = newLink;
}
else{
previous.next = newLink;
}
newLink.next = current;
} public Link remove(){
Link temp = first;
first = first.next;
return temp;
} public void displayLinkedList(){//顺链从小到大
System.out.println("sorted linkedlist---small--to--big");
Link current = first;
while(current!= null ){
current.diaplayLink();
System.out.print("");
current = current.next;
}
System.out.println();
} public static void main(String[] args) { MySortedLinkList sortlist = new MySortedLinkList(); sortlist.insert(7);
sortlist.insert(6);
sortlist.insert(9); sortlist.displayLinkedList();
} }
上一篇:关于socket tcp 断线重连


下一篇:MySQL的零碎知识点