在Java中创建一个栈和一个队列
时间: 2024-04-30 07:18:36 浏览: 66
第4章习题(栈和队列).doc
创建栈的示例代码如下:
```java
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Stack elements: " + stack);
System.out.println("Top element: " + stack.peek());
stack.pop();
System.out.println("Stack elements after pop: " + stack);
}
}
```
创建队列的示例代码如下:
```java
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("Alice");
queue.add("Bob");
queue.add("Charlie");
System.out.println("Queue elements: " + queue);
System.out.println("Front element: " + queue.peek());
queue.remove();
System.out.println("Queue elements after remove: " + queue);
}
}
```
阅读全文