package 栈与队列上;
import java.util.LinkedList;
/**
* 定义节点
* @author buder_cp
*
* @param
*/
class ListNode {
T val;
ListNode next;
public ListNode(T value, ListNode next) {
super();
this.val = value;
this.next = next;
}
}
/*
* 建立自己的队列
*/
public class MiniQueue {
private int size;
public boolean isEmpty() {
if (size == 0) {
return true;
} else {
return false;
}
}
public int size() {
return size;
}
/**
* 初始化队列,两个指针
*/
private ListNode head;
private ListNode last;
public MiniQueue() {
super();
head = new ListNode(null, null); // 初始化两个指针
last = head;
}
/**
* 从队尾添加元素
* @param t
*/
public void offer(T t) {
ListNode node = new ListNode(t, null);
last.next = node;
last = node;
size++;
}
/**
* 查看对头元素
* @return
*/
public T peek() {
if (isEmpty()) {
return null;
} else {
return head.next.val;
}
}
/*
* 弹出队列投元素
*/
public T poll() {
if (isEmpty()) {
return null;
} else {
ListNode p = head.next;
head.next = p.next;
size--;
if (size == 0) {
last = head;
}
return p.val;
}
}
public static void main(String[] args) {
MiniQueue my_queue = new MiniQueue();
System.out.println("队列初始化大小:" + my_queue.size);
my_queue.offer(1);
my_queue.offer(2);
my_queue.offer(3);
System.out.println("添加元素后大小:" + my_queue.size);
while (!my_queue.isEmpty()) {
System.out.print("弹出队列:" + my_queue.poll() + " ");
}
}
}