zoukankan      html  css  js  c++  java
  • 有序链表--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 }
  • 相关阅读:
    【转】Android开发中Handler的使用
    【转】关于微信开发者平台移动应用获取签名解决问题
    AndroidStudio开发工具快捷键
    进程与线程
    【转】Git常用命令
    Java中内存空间的分配及回收
    【转】Github入门教程
    周记
    本周工作内容及感想
    总结
  • 原文地址:https://www.cnblogs.com/sun1993/p/7680416.html
Copyright © 2011-2022 走看看