有序链表 代码实现

package firstlast;

public class SortedList {
   private Link first;
    
   public SortedList(){
    first = null;    
  }
    
   public boolean isEmpty(){
     return first == null;
  }
    
   public void insert( long key){
    Link current = first;
    Link prev = null;
    Link newLink = new Link(key);
/*    while(current !=null && key >current.dData){
      prev = current;
      current = current.next;
    }*/
    
     while(current != null){
       if(key>current.dData){
        prev =current;
        current = current.next;
      } else{
         break;
      }
    }
     // 存在三种可能,当前节点可能在表头、表中、表尾,但是表尾、表中效果一样
    
     if(prev == null){ //current == first ?
      first = newLink;
    } else{
      prev.next = newLink; //表头表尾
    }    
    newLink.next = current;
    
  }
   public void displayList(){
    Link current = first;
     while(current != null){
      current.displayLink();
      current = current.next;
    }
  }
   public static void main(String[] args){
    SortedList sortlist = new SortedList();
    sortlist.insert(12);
    sortlist.insert(10);
    sortlist.insert(30);
    sortlist.insert(5);
    sortlist.insert(0);
    sortlist.displayList();
  }
}

你可能感兴趣的:(排序,链表,职场,休闲)