有序鏈表--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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM