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

 

转载于:https://www.cnblogs.com/sun1993/p/7680416.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值