一、Java语言描述有序链表
在有序链表中数据按照关键字有序的排列,插入到有序链表中的程序如下所示:
package com.solid.link;
public class SortLink {
//对第一个链结点的引用
private Link first;
/**
* 构造方法
*/
public SortLink() {
first = null;
}
/**
* 判断是否为空
* @return
*/
public boolean isEmpty() {
return (first==null);
}
/**
* 插入到有序链表
* @param key
*/
public void insert(int key) {
Link link = new Link(key);
Link current = first;
Link previous = null;
while(current != null && key > current.iDate) {
previous = current;
current = current.next;
}
if(previous == null) {
first = link;
} else {
link.next = current;
previous.next = link;
}
}
/**
* 显示有序链表中的数据
*
*/
public void display() {
Link current = first;
while(current != null) {
current.display();
current = current.next;
}
System.out.println();
}
/**
* 有序链表测试
* @param args
*/
public static void main(String[] args) {
SortLink sortLink = new SortLink();
sortLink.insert(1);
sortLink.insert(3);
sortLink.insert(5);
sortLink.insert(10);
sortLink.insert(2);
sortLink.insert(4);
sortLink.insert(6);
sortLink.display();
}
}