4.有序链表
package link;
public class SortedLink {
private Link first = null;
private Link last = null;
public SortedLink(Link first, Link last) {
super();
this.first = first;
this.last = last;
}
public SortedLink() {
super();
this.first = null;
this.last = null;
}
public boolean isEmpty(){
return first == null;
}
/**
* 从小到大排列
* @param data
*/
public void insert(int data){
Link link = new Link(data);
if(isEmpty()){
first = link;
last = link;
}else{
Link c = first;
Link pre = null;
while(c != null && c.iData < data){
pre = c;
c = c.next;
}
if(pre == null && c!= null){//插在链表的头
first = link;
link.next = c;
}else if(c == null){//插在链表的尾部
pre.next = link;
}else{
pre.next = link;
link.next = c;
}
}
}
public void displayList(){
System.out.println("List (first ---> last):");
Link d = first;
while(d != null){
d.displayLink();
d = d.next;
}
}
}
package link;
public class SortedLinkApp {
public static void main(String args[]){
SortedLink st = new SortedLink();
st.insert(20);
st.insert(2);
st.insert(21);
st.insert(3);
st.displayList();
}
}