1 public class DequeStructure {
 2     Deque<Integer> stack1;
 3     Deque<Integer> stack2;
 4     public DequeStructure () {
 5         stack1 = new LinkedList<>();
 6         stack2 = new LinkedList<>();    
 7     }
 8     
 9     public void leftPush(int x) {
10         stack1.push(x);
11     }
12     
13     public void rightPush(int x) {
14         stack2.push(x);
15     }
16     
17     public int leftPop() {
18         if (stack1.isEmpty() && stack2.isEmpty()) {
19             return -1;
20         }
21         if (stack1.isEmpty()){
22             shuffle();
23         }
24         return stack1.pop();
25     }
26     
27     public int rightPop() {
28         if (stack1.isEmpty() && stack2.isEmpty()) {
29             return -1;
30         }
31         if (stack2.isEmpty()) {
32             shuffle();
33         }
34         return stack2.pop();
35     }
36     
37     // O(n) operations, very expensive!!
38     private void shuffle() {
39         if (stack1.isEmpty()) {
40             while (!stack2.isEmpty()) {
41                 stack1.push(stack2.pop());
42             }
43         } else {
44             while (!stack1.isEmpty()) {
45                 stack2.push(stack1.pop());
46             }
47         }
48     }
49 }

 

posted on 2018-03-20 03:56  mayinmiao  阅读(135)  评论(0编辑  收藏  举报