开头
放一点学习过程中,觉得有意思的题目。
进入题库理由
在学习数据结构的过程中,接触到了栈与队列。
栈的特性是先入后出
而队列的特性是先入先出
明明看起来并不相干,但这二者却都能在通过一点算法的帮助下实现对方。
如何用栈实现队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import java.util.Stack; public class test { private Stack<Integer> a = new Stack<Integer>(); private Stack<Integer> b = new Stack<Integer>();
public void enQueue(int element) { a.push(element); while(!a.empty()) { b.push(a.pop()); } } public Integer deQueue() { if(b.empty()) { if(a.empty()) { return null; } } return b.pop(); } public Integer top() { return b.peek(); } public boolean empty() { return b.empty(); } public static void main(String[] args) { test t = new test(); t.enQueue(1); t.enQueue(2); t.enQueue(3); t.enQueue(4); t.deQueue(); t.deQueue(); System.out.println(t.top()); System.out.println(t.empty()); } }
|
如何用队列实现栈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import java.util.LinkedList; import java.util.Queue;
public class test2 { private Queue<Integer> a = new LinkedList(); private Queue<Integer> b = new LinkedList();
public void push(int element) { a.offer(element); while(!b.isEmpty()) { a.offer(b.poll()); } Queue temp = a; a = b; b = temp; }
public int pop() { return b.poll(); }
public int top() { return b.peek(); }
public boolean empty() { return b.isEmpty(); }
public static void main(String[] args) { test2 a = new test2(); a.push(1); a.push(2); a.pop(); System.out.println(a.top()); System.out.println(a.empty()); } }
|
结尾
以上就是第一期的题库。
没错,我又在水博客了。