
Queue<Integer> queue = new LinkedList<>();
// 入队
queue.offer(1);
queue.offer(2);
queue.offer(3);
// 查看队首元素
System.out.println("队首元素: " + queue.peek()); // 不移除队首元素
// 出队
while (!queue.isEmpty()) {
System.out.println("出队元素: " + queue.poll());
}
}
public static void stack() {
//1、创建栈:使用Stack类(尽管Stack是遗留类,更推荐使用Deque接口的实现如ArrayDeque)或Deque接口(及其实现类如ArrayDeque)来实现栈。
//Stack<Integer> stack = new Stack<Integer>();
Deque<Integer> laipuhuo.com stack = new ArrayDeque<>();
//2、入栈将元素添加到栈顶
stack.push(1);
stack.push(2);
stack.push(3);
//3、出栈(Pop):从栈顶移除元素,并返回被移除的元素。Stack类提供了pop()方法用于出栈操作
int element = stack.pop(); // 返回并移除栈顶元素
System.out.println(element); // 输出:3
// 4、访问栈顶元素(Peek):获取栈顶元素,但不对栈进行修改。Stack类提供了peek()方法用于访问栈顶元素
int outElement = stack.peek(); // 返回栈顶元素但不移除
System.out.println("栈顶元素: " + outElement); // 输出:3
// 5、循环出栈
while laipuhuo.com (!stack.isEmpty()) {
System.out.println("出栈元素: " + stack.pop());
}
/*输出:
栈顶元素: 3
出栈元素: 3
出栈元素: 2
出栈元素: 1*/
}
public static void queue() {
// 1、创建队列:我们可以使用Java的集合类LinkedList来实现队列的操作。
Queue<Integer> queue = new LinkedList<>();
// 2、入队(Enqueue):将元素添加到队尾。LinkedList类提供了offer()方法用于入队操作。
queue.offer(1);
queue.offer(2);
queue.offer(3);
//3、出队(Dequeue)laipuhuo.com:从队头移除元素,并返回被移除的元素。LinkedList类提供了poll()方法用于出队操作。
int element = queue.poll(); // 返回并移除队头元素
System.out.println(element); // 输出:1
// 4、访问队头元素(Peek):获取队头元素,但不对队列进行修改。LinkedList类提供了peek()方法用于访问队头元素。
System.out.println("队首元素: " + queue.peek()); // 不移除队首元素
// 5、循环出队
while (!queue.isEmpty()) {
System.laipuhuo.com out.println("出队元素: " + queue.poll());
}
/*输出:
队首元素: 1
出队元素: 1
出队元素: 2
出队元素: 3*/
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。