import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;/**
* Class SortedLink Description 有序链表,首先的搜索链表,直到找到合适的位置,它恰好在第一个比它大的数据项的前面,
* 主要是插入是必须使整个链表有序。 Company OpenData Author Chenlly Date 09-03-05 Version 1.0
*/class Link {
public Long lData;
public Link next; // 构造方法
public Link(Long lData) {
this.lData = lData;
} // 显示链表信息
public void displayLink() {
System.out.println("" + lData + ",");
}
}public class SortedLink {
private Link firstLink;
private int size; public SortedLink() {
// to do something
firstLink = null;
} // 构造一个新节点
public Link createNode(Long lData) {
Link link = new Link(lData);
return link;
} // 插入一个新节点使整个链表有序
public void insert(Link link) {
Link current = firstLink;
Link previous = null;
//链表从头到尾,按升序排列
while (current != null && current.lData < link.lData) {
previous = current;
current = current.next;
}
if (previous == null) {
firstLink=link;//第一次插入的情况
} else {
link.next = current;
previous.next = link;
}
} // 删除一个最小的节点
public Link remove() throws Exception {
if (firstLink==null){
throw new Exception ("WARN - 链表中还没有数据项,不能做删除操作");
}
Link temp = firstLink;
firstLink = firstLink.next;
return temp;
} // 显示链表信息
public void display() {
System.out.println("from first-->end:");
Link current = firstLink;
while (current != null) {
current.displayLink();
current = current.next;
}
} // 从键盘输入数据
public static String readStr() {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
} public static void main(String[] args) {
System.out.println("链表基本算法请选择:");
System.out.println("1 插入新节点");
System.out.println("2 删除新节点");
System.out.println("3 显示链表信息");
System.out.println("4 退出");
SortedLink sortedLink = new SortedLink();
while (true) {
System.out.println("请输入操作序列:");
int op = Integer.parseInt(SortedLink.readStr());
switch (op) {
case 1:
System.out.println("请输入节点信息");
Long lData = new Long(Long.parseLong(SortedLink.readStr()));
Link newLink = sortedLink.createNode(lData);
sortedLink.insert(newLink);
break;
case 2:
Link oldLink = null;
try {
oldLink = sortedLink.remove();
} catch (Exception ex){
ex.printStackTrace();
}
if (oldLink != null) {
System.out.println("删除的节点信息:" + oldLink.lData);
} else {
System.out.println("删除节点失败");
}
break;
case 3:
sortedLink.display();
break;
case 4:
default:
System.exit(0);
}// end switch
}// end while
}
}