主要学习了链队列
用数组实现的队列叫顺序队列,用链表实现的队列叫链式队列。
链式队列的插入只能在队尾进行,删除在队头进行。
链队列的两个状态和两个操作:
(1)两个状态:
1)队列为空
2)队列为满
队列不为满时的两个操作
1)插入入队(队尾操作)
2)删除出队(队首操作)
今天的代码主要是实现链队列的插入和删除操作
package second;
/**
* Linked queue.
*
* @author 纪龙
*
*/
public class LinkedQueue {
/**
* An inner class.
*/
class Node {
/**
* the data
*/
int data;
/**
* The reference to the next node.
*/
Node next;
/**
* The constructor.
*
* @param value The data.
*/
public Node(int value) {
data = value;
next = null;
}
}
/**
* The header of the queue.
*/
Node header;
/**
* The tail of the queue.
*/
Node tail;
/**
* Construct an empty sequential list.
*/
public LinkedQueue() {
header = new Node(0);
tail = header;
}
/**
* Overrides the method claimed in Objects,the superclass of any class.
*/
public String toString() {
String resultString = "";
if (header.next == null) {
return "empty";
}
Node tempnode = header.next;
while (tempnode != null) {
resultString += tempnode.data + ", ";
tempnode = tempnode.next;
}
return resultString;
}
/**
* Enqueue.
*
* @param value The value of the new node.
*/
public void enqueue(int value) {
Node node = new Node(value);
tail.next = node;
tail = node;
}
/**
* Dequeue.
*
* @return The value at the header.
*/
public int dequeue() {
if (header == tail) {
System.out.println("The queue is empty. ");
return -1;
}
int resultvalue = header.next.data;
header.next = header.next.next;
if (header.next == null) {
tail = header;
}
return resultvalue;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedQueue tempqueue = new LinkedQueue();
System.out.println("Initialized, the list is: " + tempqueue.toString());
for (int i = 0; i < 5; i++) {
tempqueue.enqueue(i);
}
System.out.println("Enqueue,the queue is: " + tempqueue);
tempqueue.dequeue();
System.out.println("Dequeue,the queue is: " + tempqueue.toString());
int tempvalue;
for (int i = 0; i < 5; i++) {
tempvalue = tempqueue.dequeue();
System.out.println("Looped delete " + tempvalue + " ,the queue is " + tempqueue.toString());
}
for (int i = 0; i < 3; i++) {
tempqueue.enqueue(i + 10);
System.out.println("Enqueue,the queue is: " + tempqueue.toString());
}
}
}