package datastructure.queue;
public class linkedQueue {
class Node {
int data;
Node next;
public Node(int paraValue) {
// TODO Auto-generated constructor stub
data = paraValue;
next = null;
}//of the constructor
}//of class Node
Node header;
Node tail;
public linkedQueue() {
// TODO Auto-generated constructor stub
header = new Node(-1);//header.next = null
tail = header;
}//of the first constructor
public void enqueue(int paraValue) {
Node tempNode = new Node(paraValue);
//System.out.println(paraValue);
tail.next = tempNode;
tail = tempNode;
}//of enqueue
public int dequeue() {
if (header == tail) {
System.out.println("No element in the queue!");
return -1;
}//of if
int resultValue;
resultValue = header.next.data;
header.next = header.next.next;
if (header.next == null) {
header = tail;
}//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[]) {
linkedQueue tempQueue = new linkedQueue();
System.out.println("Initialized, the list is: " + tempQueue.toString());
for (int i = 0; i < 5; i++) {
tempQueue.enqueue(i + 1);
//System.out.println(i);
}//of for i
System.out.println("Enqueue, the queue is: " + tempQueue.toString());
tempQueue.dequeue();
System.out.println("Dequeue, the queue is: " + tempQueue.toString());
}//of main
}//of linkedQueue
代码中的输出语句是调试时候添加的,已经注释掉了。今天的代码刚写完运行结果不正确,运行结果如下:
在主函数的for循环中添加了输出语句,发现i值正确,考虑是入队函数的问题;在入队函数里添加输出语句,数值也是正确的;遂考虑是toString()函数有问题。后面发现闵老师代码里是resultString += tempNode.data + “,”;而自己写成了resultString += tempNode.data + ‘,’;把双引号写成了单引号。百度了一下逗号的ASCII码刚好是44,也就是说我写的代码resultString的值是tempNode.data加上逗号的ASCII码(44)。
起初还是不理解,又去百度了一下Java中单引号和双引号的区别:java中单引号表示字符,双引号是字符串;单引号的数据一般是char类型,双引号的数据是String类型。思考了一下,后面是双引号,那么当i=1时,resultString为1和“,”,是一个字符串;如果后面是单引号,就是一个int数据和一个char数据相加,就会被强制转换为int数据。
最终程序的运行结果如下:



