链式队列
package practice;
//链式队列
class TestLinkQueue {
class Entry{
int data;
Entry next;
public Entry (){
data = -1;
next = null;
}
public Entry(int data){
this.data = data;
next = null;
}
}
private Entry front = null;
private Entry rear = null;
private int usedSize = 0;
//是否为空
public boolean isEmpty(){
return this.usedSize == 0;
}
//入队
public void insertTail(int val){
if(isEmpty()){
this.rear = new Entry(val);
this.front = this.rear;
}else{
this.rear.next = new Entry(val);
this.rear = this.rear.next;
}
this.usedSize++;
}
//出队
public void pop(){
if(isEmpty()){
return;
}
Entry cur = this.front;//cur用来指向出队的元素,以便制空
this.front = cur.next;
cur.next = null;
this.usedSize--;
}
//得到队头元素
public int getTop(){
if(isEmpty()){
return -1;
}
return this.front.data;
}
//show
public void show(){
Entry cur = this.front;
while(cur != null){
System.out.print(cur.data+" ");
cur = cur.next;
}
System.out.println();
}
}
public class TestLinkQ {
public static void main(String[] args) {
TestLinkQueue t1 =new TestLinkQueue();
t1.insertTail(10);
t1.insertTail(20);
t1.insertTail(30);
System.out.print("队内元素:");
t1.show();
t1.pop();
System.out.print("出队后队内元素:");
t1.show();
System.out.println("队头元素为:"+t1.getTop());
}
}
优先级队列
package practice;
/*
* 优先级队列:按照优先级进行存储数据
* */
class Priolink1{
class Entry{
int data;
int prio;
Entry next;
public Entry(){
data = -1;
prio = -1;
next = null;
}
public Entry(int data,int prio){
this.data = data;
this.prio = prio;
this.next = null;
}
}
private Entry head = null;
public Priolink1(){
this.head = new Entry();
}
//插入,按照优先级进行插入
public void insert(int data,int prio){
Entry entry = new Entry(data,prio);
Entry cur = head;
while(cur.next != null){
if(cur.next.prio>prio){
break;
}
cur = cur.next;
}
entry.next = cur.next;
cur.next = entry;
}
//出队
public void pop(){
Entry cur = this.head;
if(cur.next == null){
return;
}
Entry del = cur.next;
cur.next = del.next;
del = null;
}
//show
public void show(){
Entry cur = this.head.next;
while(cur != null){
System.out.print(cur.data+" ");
cur = cur.next;
}
System.out.println();
}
}
public class PrioLink {
public static void main(String[] args) {
Priolink1 t1 = new Priolink1();
t1.insert(1, 1);
t1.insert(10, 10);
t1.insert(5, 5);
System.out.print("队内元素:");
t1.show();
t1.pop();
System.out.print("出队后元素:");
t1.show();
}
}