队列是一种特殊的线性表,主要的特点在于其添加数据是在队尾进行操作的而删除数据是在队首进行操作的。
首先定义Node类:
class Node {
int data;//定义节点元素
Node next;//定义节点指针
//定义构造方法
public Node(int paraValue) {
data = paraValue;
next = null;
}
}
实现对链队列的几种操作,判断是否空、入队、出队、取队首值、取队尾值、求长度等
1、判断是否空
public boolean isempty(){
if(head==null) {
return true;
}
return false;
}
2、入队
public void enqueue(int paraValue) {
Node tempNode = new Node(paraValue);
tail.next = tempNode;
tail = tempNode;
}
3、出队
public int dequeue() {
if (header == tail) {
System.out.println("No element in the queue");
return -1;
}
int resultValue = header.next.data;
header.next = header.next.next;
if (header.next == null) {
tail = header;
}
return resultValue;
}
4、取队首值:
public void headnum() {
if(isempty()) {
System.out.println("队列已空");
}else {
System.out.println("队首值是:"+head.data);
}
}
5、取队尾值
public void rearnum() {
Node nextNode=rear;
while(nextNode.next!=null) {
nextNode=nextNode.next;
}
if(isempty()) {
System.out.println("队列已空");
}else {
System.out.println("队尾的值是:"+nextNode.data);
}
}
6、求队长值
public void length() {
Node nextNode=head;
int i=0;
if(isempty()) {
System.out.println("队列为空");
}else {
while(nextNode!=null) {
i++;
nextNode=nextNode.next;
}
}
System.out.println("队列的长度是:"+i);
}
实战:简单实现进队与出队操作
package day_19;
public class day19 {
class Node {
int data;
Node next;
public Node(int paraValue) {
data = paraValue;
next = null;
}
}
Node header;
Node tail;
public day19() {
header = new Node(-1);
// header.next = null;
tail = header;
}
public void enqueue(int paraValue) {
Node tempNode = new Node(paraValue);
tail.next = tempNode;
tail = tempNode;
}
public int dequeue() {
if (header == tail) {
System.out.println("No element in the queue");
return -1;
} // Of if
int resultValue = header.next.data;
header.next = header.next.next;
// The queue becomes empty.
if (header.next == null) {
tail = header;
} // Of if
return resultValue;
}// Of dequeue
public String toString() {
String resultString = "";
if (header.next == null) {
return "empty";
} // Of if
Node tempNode = header.next;
while (tempNode != null) {
resultString += tempNode.data + ", ";
tempNode = tempNode.next;
} // Of while
return resultString;
}// Of toString
public static void main(String args[]) {
day19 tempQueue = new day19();
System.out.println("Initialized, the list is: " + tempQueue.toString());
for (int i = 0; i < 5; i++) {
tempQueue.enqueue(i + 1);
} // Of for i
System.out.println("Enqueue, the queue is: " + tempQueue.toString());
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 new queue is: " + tempQueue.toString());
} // Of for i
for (int i = 0; i < 3; i++) {
tempQueue.enqueue(i + 10);
}
System.out.println("Enqueue, the queue is: " + tempQueue.toString());
}// Of main
}
结果为: