栈和队列

2016-11-06  本文已影响0人  Recker

两个栈实现队列


 private List<String> mStack1 = new ArrayList<>();
 private List<String> mStack2 = new ArrayList<>();
 
 private void appendTail(String str) {
     mStack1.add(str);
 }
 
 private String deleteHead() {
    if(mStack1.size() > 0) {
       for(int i = mStack1.size()-1; i >= 0; --i) {
          mStack2.add(mStack1.get(i));
          mStack1.remove(i);
       }
    }
  
    if (mStack2.size() == 0)
        return null;
  
    int last = mStack2.size()-1;
    String head = mStack2.get(last);
    mStack2.remove(last);
  
    return head;
 }

两个队列实现栈


 private List<String> mStack1 = new ArrayList<>();
 private List<String> mStack2 = new ArrayList<>();
 
 private void appendTail(String str) {
    mStack1.add(str);
 }
 
 private String deleteHead() {
    String head = null;
  
    if(mStack1.size() > 1) {
       while(mStack1.size() > 1) {
       mStack2.add(mStack1.get(0));
          mStack1.remove(0);
       }
    }
  
    if(mStack1.size() == 1) {
       head = mStack1.get(0);
       mStack1.clear();
       return head;
    }
  
    if(mStack2.size() > 1) {
       while(mStack2.size() > 1) {
           mStack1.add(mStack2.get(0));
           mStack2.remove(0);
       }
    }
  
    if(mStack2.size() == 1) {
       head = mStack2.get(0);
       mStack2.clear();
       return head;
    }
  
    return null;
 }
上一篇 下一篇

猜你喜欢

热点阅读