java数据结构——链表实现队列
package fwb.COllection;
public class Queue<T> {
class Node{
T val;
Node next;
public Node(T val,Node next){
this.val = val;
this.next = next;
}
Node(T val){
this(val,null);
}
}
private Node head = null;
private Node tail = null;
int size = 0;
public boolean isEmpty(){
return size == 0;
}
public int size(){
return size;
}
public void enqueue(T var){
Node node = new Node(var);
if(tail ==null){
head = node;
}else{
tail.next = node;
}
tail = node;
size++;
}
public T dequeue(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
Node oldHead = head;
head = head.next;
if(head == null){
tail =null;
}
size--;
return oldHead.val;
}
public T peek(){
if(isEmpty()){
throw new RuntimeException("队列空");
}
return head.val;
}
public void show(){
Node p = head;
while(p!=null){
System.out.println(p.val);
p = p.next;
}
}
public static void main(String[] args) {
Queue<Integer> queue = new Queue<>();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println("元素个数:"+queue.size());
queue.show();
System.out.println("队头元素:"+queue.peek());
int result = queue.dequeue();
System.out.println("出队元素:"+result);
System.out.println("出队后队头元素:"+queue.peek());
}
}