package shousi;
/**
* 用链表表示队列
*/
public class Test49 {
private int size;
private Node head;//头节点
private Node tail;//尾节点
public Test49(){ //初始化
size = 0;
head = null;
tail = null;
}
class Node{
public Object data;// 每个节点的数据
public Node next;// 每个节点指向下一个节点的连接
public Node(Object data) {
this.data = data;
}
}
/**
* 向队尾添加元素
根据传递进来的值创建节点。
判断添加的是否是第一个节点,若是则将头节点设置为当前节点,
若不是则将当前尾节点的next设置为当前节点。
再将当前节点设置为尾节点,size自增一。
*/
public void insertTail(Object value){
Node newNode = new Node(value);
if (size == 0) {
head = newNode;
}else {
tail.next = newNode;
}
tail = newNode;
size++;
}
/**
* 向队头删除元素
判断队列是否为空,为空不可删除。
将头节点设置为头节点的next,size自减一。
判断删除节点之后队列是否为空,若为空队列将尾节点指向空。
*/
public Node delectHead(){
if (size != 0) {
head = head.next;
size--;
if (size == 0) {
tail = null;
}
return head;
}else {
return null;
}
}
/**
* 判断队列是否为空
*/
public boolean isNull() {
return size == 0;
}
/**
* 打印节点信息
*/
//打印
public void printNode() {
if (size > 0) {
Node node = head;
if (size == 1) {
System.out.println("["+node.data+"]");
return;
}
int item = size;
System.out.print("[");
while (item > 0) {
if (node.next == null) {
System.out.print(node.data + "]");
}else {
System.out.print(node.data + ",");
}
node = node.next;
item--;
}
}else {
System.out.println("[]");
}
}
}
11-27
416
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-13
2388
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-01
166
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交