/**
* 节点类
*/
class NodeI {
public long data;
public NodeI next;
public NodeI(long d) {
this.data = d;
}
}
/**
* 排序链表
*/
class SortedListI {
private NodeI first;
public SortedListI() {
this.first = null;
}
//构造函数传入要排序的节点数组
public SortedListI(NodeI[] arr) {
first = null;
for (int i = 0; i < arr.length; i++) {
insert(arr[i]);
}
}
//内部封装一个排序方法,供构造函数初始化使用
private void insert(NodeI i) {
NodeI previous = null;
NodeI current = first;
while (current != null && i.data > current.data) {
previous = current;
current = current.next;
}
if (previous == null) {
first = i;
} else {
previous.next = i;
}
i.next = current;
}
//移除头部
public NodeI remove() {
NodeI temp = first;
first = first.next;
return temp;
}
//判断链表是否为空
public boolean isEmpty() {
return first == null;
}
public String toString() {
if (isEmpty())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append("[");
NodeI n = first;
while (n != null) {
sb.append(n.data + ",");
n = n.next;
}
sb.deleteCharAt(sb.length() - 1);
sb.append("]");
return sb.toString();
}
public void display(){
System.out.println(toString());
}
}
public class ListInsertSortDemo {
public static void main(String[] args) {
int size = 10;
NodeI[] array = new NodeI[size];
for (int i = 0; i < size; i++) {
int n = (int) (Math.random() * 99);
NodeI node = new NodeI(n);
array[i] = node;
}
System.out.println("未经排序的数组:");
for (int i = 0; i < size; i++) {
System.out.print(array[i].data + " ");
}
System.out.println();
SortedListI sl = new SortedListI(array);
System.out.println("经过排序链表初始化后,链表为:");
sl.display();
}
}