首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

数据结构跟算法

2012-11-08 
数据结构和算法4.有序链表package linkpublic class SortedLink {?private Link first null?private L

数据结构和算法

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();
??
??
??
??
?}
}

热点排行