1. 程式人生 > >有序連結串列實現優先佇列

有序連結串列實現優先佇列

/**
 * 有序連結串列的優先佇列
 *
 */
class Lin {
	public int data;
	public Lin next;
	public Lin(int i) {
		data=i;
	}
	public void displayLin() {
		System.out.print(data+" ");
	}
}
class LinList {
	private Lin first;
	public LinList() {
		first=null;
	}
	public void insert(int key) {
		Lin newLink=new Lin(key);
		Lin previous=null;
		Lin current=first;
		while(current!=null && newLink.data>current.data) {
			previous=current;
			current=current.next;
		}
		if(previous==null) {
			first=newLink;
		} else {
			previous.next=newLink;
		}
		newLink.next=current;
	}
	public Lin delete() {
		Lin tmp=first;
		first=first.next;
		return tmp;
	}
	public void displayLinList() {
		Lin current=first;
		while(current!=null) {
			current.displayLin();
			current=current.next;
		}
	}
}
public class Five_1 {
	public static void main(String[] args) {
		LinList ll=new LinList();
		for(int i=0;i<10;i++) {
			int k=(int)(Math.random()*100);
			ll.insert(k);
		}
		ll.displayLinList();
		System.out.println();
		ll.delete();
		ll.displayLinList();
	}
	
}