分析
在大多数的有序数组的使用情况下都可以使用有序链表,且有序列表的性能要优于有序数组主要表现在连个方面
1:有序的链表插入速度快 (链表不要移动)
2:链表可以拓展到全部有效内存,而数组只能限于一个固定的大小中
话不多说直接上代码
package com.yc.Link;
//节点类
public class Link {
private int idate;
private double ldate;
private Link next;
public Link(int idate, double ldate) {
super();
this.idate = idate;
this.ldate = ldate;
}
public Link(int idate) {
super();
this.idate = idate;
}
public int getIdate() {
return idate;
}
public void setIdate(int idate) {
this.idate = idate;
}
public double getLdate() {
return ldate;
}
public void setLdate(double ldate) {
this.ldate = ldate;
}
public Link getNext() {
return next;
}
public void setNext(Link next) {
this.next = next;
}
@Override
public String toString() {
return "Link [idate=" + idate + ", ldate=" + ldate + ", next=" + next + "]";
}
}
SortLink类
package com.yc.Link;
public class SortLink {
private Link first;//头结点
//constructor
public SortLink() {
first=null;
}
//移除元素只支持从头部开始移除
public Link remove() {
Link temp=first;
first=first.getNext();
return temp;
}
//展示链表元素
public void display() {
System.out.print("List -->last:");
Link current=first;
while(current!=null) {
System.out.print("-->"+current.getIdate());
current=current.getNext();
}
System.out.println("");
}
//插入元素
public void insert(int key ) {
Link newLink=new Link(key);
Link previo=null;//前一个位置的结点
Link courrent=first;//当前位置的结点
//寻找插入位置
//跳出循环的courent为要插入的结点位置的前一个结点
while(courrent!=null && courrent.getIdate()<key) {
previo=courrent;
courrent=courrent.getNext();
}
//插入的位置为头结点(即链表表头的时候)
if(previo==null) {
//直接插入头结点
first=newLink;
}else {
//当插入的位置其他位置的时候
previo.setNext(newLink);
}
newLink.setNext(courrent);
}
//测试
public static void main(String[] args) {
SortLink sort=new SortLink();
sort.insert(8);
sort.insert(5);
sort.display();
sort.insert(1);
sort.insert(4);
sort.display();
}
}
运行效果