堆棧和隊列統稱線性表數組
簡單的線性結構數據結構
數組和鏈表能夠實現這兩種數據結構this
堆棧設計
基本理解code
DFS遞歸
深度優先---按深度遍歷隊列
遞歸轉非遞歸element
隊列rem
基本理解it
BFS
廣度優先---按層序遍歷
出入棧的合法性
模擬出入棧的過程,不是入棧,就是出棧,否則就不合法
public boolean isPossible(int[] in, int[] out){ if(in.length != out.length){ return false; } Stack<Integer> s = new Stack<>(); for(int i = 0, j = 0;j < out.length; j++){ //若是不是入棧的 while(s.isEmpty() && s.peek() != out[j]){ if(i >= in.length){ return false; } s.push(in[i++]); } //那就出棧 s.pop(); } return true; }
兩個棧實現隊列
public class MyQueue{ Stack<Integer> s1 = new Stack<>(); Stack<Integer> s2 = new Stack<>(); public void push(int x){ s1.push(x); } //負負得正 public int pop(){ if(s2.isEmpty()){ while(!s1.isEmpty()){ s2.push(s1.pop()); } } return s2.pop(); } public int peek(){ if(s2.isEmpty()){ while(!s1.isEmpty()){ s2.push(s1.pop()); } } return s2.peek(); } public boolean empty(){ return s1.isEmpty() && s2.isEmpty(); } }
兩個隊列實現棧
public class MyStack { Queue<Integer> queue1; Queue<Integer> queue2; /** Initialize your data structure here. */ public MyStack() { queue1 = new LinkedList<>(); queue2 = new LinkedList<>(); } /** Push element x onto stack. */ public void push(int x) { if(!queue1.isEmpty()){ queue1.offer(x); }else{ queue2.offer(x); } } /** Removes the element on top of the stack and returns that element. */ public int pop() { if(queue1.size() != 0){ while(queue1.size() > 1){ queue2.add(queue1.peek()); queue1.poll(); } return queue1.remove(); }else{ while(queue2.size() > 1){ queue1.add(queue2.peek()); queue2.poll(); } return queue2.remove(); } } /** Get the top element. */ public int top() { if(queue1.size() != 0){ while(queue1.size() > 1){ queue2.add(queue1.poll()); } int res = queue1.peek(); queue2.add(queue1.poll()); return res; }else{ while(queue2.size() > 1){ queue1.add(queue2.poll()); } int res = queue2.peek(); queue1.add(queue2.poll()); return res; } } /** Returns whether the stack is empty. */ public boolean empty() { return queue1.isEmpty() && queue2.isEmpty(); } }
設計一個棧,除pop與push方法,還支持min方法,可返回棧元素中的最小值。push、pop和min三個方法的時間複雜度必須爲O(1)
兩種解法,解法一,將最小值存入自有的數據結構中,以下所示
public class MyStack extends Stack<NodeWithMin>{ public void push(int value){ int newMin = Math.min(value, min()); super.push(new NodeWithMin(value, newMin)); } public int min(){ if(this.isEmpty()){ return Integer.MAX_VALUE; }else{ return peek().min; } } public int pop(){ super.pop().value; } } class NodeWithMin{ int value;//本來的值 int min;//最小值 public NodeWithMin(int value, int min){ this.value = value; this.min = min; } }
解法二,用兩個棧
public class MyStack{ Stack<Integer> s1 = new Stack<>(); Stack<Integer> s2 = new Stack<>(); public void push(int i){ s1.push(i); if(s2.isEmpty() || min() >= i){ s2.push(i); } } public int pop(){ if(s1.peek() == min()){ s2.pop(); } return s1.pop(); } public int min(){ return s2.peek(); } }