有序链表--Java实现
1 /*有序链表--使用的是单链表实现 2 *在插入的时候保持按照值顺序排列 3 *对于删除最小值的节点效率最高--适合频繁的删除最小的节点 4 * */ 5 public class MySortedLinkList { 6 public Link first; 7 8 public MySortedLinkList() { 9 first = null; 10 } 11 12 public boolean isEmpty(){ 13 return first == null; 14 } 15 16 public void insert(int key){ 17 Link newLink = new Link(key); 18 Link previous = null; 19 Link current = first; 20 while(current != null && key > current.id){ //找下个节点 21 previous = current; 22 current = current.next; 23 } 24 //比当前节点值小,刚好插入当前节点前面 25 if(previous == null){//链表是空的 26 first = newLink; 27 } 28 else{ 29 previous.next = newLink; 30 } 31 newLink.next = current; 32 } 33 34 public Link remove(){ 35 Link temp = first; 36 first = first.next; 37 return temp; 38 } 39 40 public void displayLinkedList(){//顺链从小到大 41 System.out.println("sorted linkedlist---small--to--big"); 42 Link current = first; 43 while(current!= null ){ 44 current.diaplayLink(); 45 System.out.print(""); 46 current = current.next; 47 } 48 System.out.println(); 49 } 50 51 52 53 54 public static void main(String[] args) { 55 56 MySortedLinkList sortlist = new MySortedLinkList(); 57 58 sortlist.insert(7); 59 sortlist.insert(6); 60 sortlist.insert(9); 61 62 sortlist.displayLinkedList(); 63 } 64 65 }