P59、面试题7:用两个栈实现队列
题目:用两个栈实现一个队列。队列声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列为插入结点和在队列头部删除结点的功能。
stack1专门用于插入数据,stack2专门用于删除数据,如果stack2没有数据了,则将stack1的数据转移到stack2中,直到两个栈都没有数据。
测试用例:
1)往空的队列里添加、删除元素
2)往非空的队列里添加、删除元素
3)连续删除元素直到队列为空
Queue类:
package com.yyq; import java.util.Stack; /** * Created by Administrator on 2015/9/8. */ public class Queue<T> { private T value; public static final Stack stack1 = new Stack(); public static final Stack stack2 = new Stack(); public T getValue() { return value; } public void setValue(T value) { this.value = value; } public Queue(){ } public void appendTail(T value){ stack1.push(value); } public T deleteHead(){ T temp; if (stack2.size() <= 0){ while(stack1.size() > 0){ temp = (T)stack1.pop(); stack2.push(temp); } } if (stack2.size() == 0){ System.out.println("The Queue is empty!!"); } return (T)stack2.pop(); } }
实现类:
package com.yyq; /** * Created by Administrator on 2015/9/8. */ public class QueueWithTwoStacks { void Test(char actual, char expected) { if(actual == expected) System.out.println("Test passed.\n"); else System.out.println("Test failed.\n"); } public static void main(String args[]){ QueueWithTwoStacks queueWithTwoStacks = new QueueWithTwoStacks(); Queue<Character> queue = new Queue<Character>(); queue.appendTail('a'); queue.appendTail('b'); queue.appendTail('c'); queue.appendTail('d'); queue.appendTail('e'); queue.appendTail('f'); char head = queue.deleteHead(); queueWithTwoStacks.Test(head, 'a'); head = queue.deleteHead(); queueWithTwoStacks.Test(head, 'b'); queue.appendTail('g'); head = queue.deleteHead(); queueWithTwoStacks.Test(head, 'c'); queue.appendTail('h'); head = queue.deleteHead(); queueWithTwoStacks.Test(head, 'd'); head = queue.deleteHead(); queueWithTwoStacks.Test(head, 'e'); } }
输出结果:
Test passed.
Test passed.
Test passed.
Test passed.
Test passed.
Process finished with exit code 0