栈
@Test
public void test5() {
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
int result = stack.pop();
System.out.println("出栈的是: " + result);
System.out.println("栈中仍存在的元素为 " + stack);
stack.push(3);
result = stack.peek();//查看堆栈顶部的对象,但不从堆栈中移除它
System.out.println("栈堆顶部的对象是: " + result);//3
boolean flag = stack.empty();
System.out.println("stack是否为空: " + flag);
int location = stack.search(1);
System.out.println("栈中1的位置为: " + location);
}
队列(Queue)
LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用
因为add()和remove()方法在失败的时候会抛出异常,所以这里添加元素用offer(),删除元素用poll()
poll():返回第一个元素,并在队列中删除
@Test
public void test5() {
Queue<String> queue = new LinkedList<String>();
queue.offer("a");
queue.offer("b");
queue.offer("c");
System.out.print("队列中的元素有:");
for(String q : queue){
System.out.print(q+"\t");
}
System.out.print("\n");
String s = queue.poll();//返回第一个元素,并在队列中删除
System.out.println("删除的元素是:"+s);
System.out.print("队列中的元素有:");
for(String q : queue){
System.out.print(q+"\t");
}
System.out.print("\n");
String s2 = queue.element();
System.out.println("现在第一个元素是:"+s2);//返回第一个元素
String s3 = queue.peek();
System.out.println("现在第一个元素是:"+s3);//返回第一个元素
}
例题 用栈实现队列
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
public class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<Integer>();
outStack = new Stack<Integer>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if(outStack.empty()==true){
while(inStack.empty()==false){
outStack.push(inStack.pop());
}
}
return outStack.pop();
}
public int peek() {
if(outStack.empty()==true){
while(inStack.empty()==false){
outStack.push(inStack.pop());
}
}
return outStack.peek();
}
public boolean empty() {
boolean flag = inStack.empty() && outStack.empty();
return flag;
}
}
用队列实现栈
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
public void push(int x) {
queue2.offer(x);
while(queue1.isEmpty()==false){
queue2.offer(queue1.poll());
}
Queue<Integer> temp = new LinkedList<Integer>();
temp = queue1;
queue1 = queue2;
queue2 = temp;
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}