import java.util.Scanner;
//栈的尾哨兵链表实现,自己实现的是尾部节点,然而视频是头节点,哈哈哈
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入队的容量");
int n = sc.nextInt();
Queue1<Integer> q = new Queue1<>(n);
System.out.println(q.isempty());
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.query();
System.out.println();
System.out.println(q.pop());
System.out.println(q.peektail());
System.out.println(q.peekhead());
System.out.println(q.isempty());
System.out.println(q.size);
q.query();
}
public static class Queue1<E> {
Node<E> tail = new Node<>(null, null);//尾节点
int capacity;//最大容量
int size = 0;//实际大小
public Queue1(int capacity) {
this.capacity = capacity;
}
public boolean push(E value) {//进队
if (size >= capacity) {
System.out.println("队已满,插入失败");
return false;
}
Node<E> p = new Node<>(value, tail.next);
tail.next = p;
size++;
return true;
}
public E pop() {//出队
if (isempty()) {
System.out.println("队为空,删除失败");
return null;
}
Node p = querysecond().next;
querysecond().next = null;
size--;
return (E) p.value;
}
public E peektail() {//查询队尾
if (isempty()) {
System.out.println("队为空,查询失败");
return null;
}
return (E) tail.next.value;
}
public E peekhead() {//查询队头
if (isempty()) {
System.out.println("队为空,查询失败");
return null;
}
Node p;
for (p = tail; p.next != null; p = p.next) {
}
return (E) p.value;
}
public Node<E> querysecond() {//查询队头的后一个
if (isempty()) {
System.out.println("队为空,查询失败");
return null;
}
Node p;
for (p = tail; p.next.next != null; p = p.next) {
}
return p;
}
public boolean isempty() {//判空
if (size == 0) {
return true;
}
return false;
}
public int size() {//返回队大小
return size;
}
public void query() {//遍历队
if (tail.next == null) {
System.out.println("队为空,遍历失败");
return;
}
for (Node p = tail.next; p != null; p = p.next) {
System.out.print(p.value + " ");
}
}
static class Node<E> {
E value;
Node next;
public Node(E value, Node next) {
this.value = value;
this.next = next;
}
}
}
}