队列与栈是很相似的,队列的特点是先进先出,形象的比喻是食堂吃饭时的排队,先排队的先拿到饭菜,先出队
与栈相同,队列也可以用链表或者数组实现,使用数组实现是一般是实现为循环队列,这样不会形成虚假的数组下标异常。
实现思路:
1、队列是先进先出,联想到食堂排队,则是从尾端加入,队头出队,所以需要定位队头front和队尾rear。
2、入队:a、如果队为空则front=newNode;rear=front;b、如果队头与队尾指向同一个节点则rear=newNode;front.next=newNode。c、如果队头和队尾不指向同一节点,则队尾rear.next=newNode;rear=newNode.
3、出队;a、如果队头和队尾指向同一节点则front=null;rear=null;b、如果不指向同一节点则返回队头front的值,front=front.next;
4、读取队头元素;
代码:
package datastu.queue;
public class Node
{
Node
next;
T value;
public Node(T value){
this.value=value;
}
public Node(Node
next, T value) {
super();
this.next = next;
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((next == null) ? 0 : next.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (next == null) {
if (other.next != null)
return false;
} else if (!next.equals(other.next))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
package datastu.queue;
public class Queue
{
Node
front; Node
rear; int size = 0; public int getSize(){ return this.size; } public boolean isEmpty(){ return false; } public void enQueue(T value){ Node
newNode = new Node
(value); if(front==null){ front = newNode; rear = front; this.size++; return; } if(rear==front){ rear = newNode; front.next=rear; this.size++; return; } Node
tem = rear; tem.next=newNode; rear = newNode; this.size++; } public T deQueue(){ Node
tem = front; if(front==null){ return null; } if(rear==front){ rear=null; front=null; this.size--; return tem.value; } front = tem.next; this.size--; return tem.value; } public T peek(){ if(front==null){ return null; } return front.value; } public static void main(String[] args) { Queue
queue = new Queue
(); for ( int i = 0; i < 10; i++ ) { queue.enQueue(i); } for(int i= 0;i<10;i++){ System.out.println(queue.deQueue()); } } }