Java实现--有序链表

《Java数据结构和算法》有感而出,最好自己先尝试实现一遍。 

代码中有详细的注释:

/**
 * 定义一个结点类
 * @author Administrator
 *
 */
public class Link {
	public int data;	//数据域
	public Link next;	//指向下一个结点
	
	public Link(int data) {
		super();
		this.data = data;
	}
	
	//打印结点的数据域
	public void diaplayLink() {
		System.out.print("{"+ data + "} ");
	}
}
/**
 * 建立有序链表
 * @author Administrator
 *
 */
public class SortedList {
	
	private Link first;
	
	public SortedList() {
		first = null;
	}
	
	public boolean isEmpty() {
		return first==null;
	}
	
	public void insert(int num) {
		Link newNode = new Link(num);	//定义一个新结点
		Link current = first;			//定义一个current结点,将first赋给它
		Link previous = null;			//定义先前结点 将previous赋为null
		
		//条件:
		//1、当前结点current不为null(包括链表不为空的情况)
		//2、新结点newNode.data的值比当前结点curren.data大 
		//满足上述两个条件则遍历链表,直到不满足上述任一条件
		while((current!=null)&&(newNode.data>current.data)) {
			previous = current;		
			current = current.next;
		}
		//只要previous不为null,这里用previous比用current/first是有优势的,
		//previous==null即可以表示链表为空的情况,又可以表示新结点的值是最小的两种情况的任一种
		if(previous==null) {
			newNode.next = first;
			first = newNode;
		}else {	//若previous不为null,就变成了两个结点插入一个结点的问题
				//当然也包含了在最后一个结点插入,效果是一样的
			previous.next = newNode;
			newNode.next = current;
		}
	}
	
	//头部删除法
	public Link remove() {
		Link temp =first;
		first = first.next;
		return temp;
	}

	
	public void displayList() {
		System.out.print("List(first--->last): ");
		Link current = first;
		while(current!=null) {
			current.diaplayLink();
			current = current.next;
		}
		System.out.println();
	}
	
}
/**
 * 测试有序数列
 * @author Administrator
 *
 */
public class TestSortedList {
	public static void main(String[] args) {
		SortedList theList = new SortedList();
		theList.insert(10);
		theList.insert(80);
		theList.insert(60);
		theList.insert(40);
		theList.insert(20);
		theList.insert(90);
		theList.insert(30);
		theList.insert(70);
		theList.insert(50);
		theList.insert(100);
		
		theList.displayList();
		
		theList.remove();
		theList.remove();
		theList.displayList();
		
	}
}

 测试结果:

List(first--->last): {10} {20} {30} {40} {50} {60} {70} {80} {90} {100} 
List(first--->last): {30} {40} {50} {60} {70} {80} {90} {100} 
 

有序链表的效率:
     在有序链表插入和删除某一项最多需要O(N)次比较(平均N/2),因为必须沿着链表上一步一步走
才能找到正确的位置。然而,可以在O(1)的时间内找到活删除最小值,因为它总在表头,如果一个应用
频繁地存取最小项,且不需要快速的插入,那么有序链表是一个有效的方案选择。例如,优先级队列可以用
有序链表来实现。

猜你喜欢

转载自blog.csdn.net/szlg510027010/article/details/82891534