# 順序棧與鏈式棧的圖解與實現java
top
),相應的 表頭就是棧底(bottom
),棧頂和棧頂是兩個指針用來表示這個棧push
或壓棧。pop
或出棧。對於壓棧和出棧,咱們分別基於順序棧和鏈棧來分析top
指針指向棧頂元素的位置top=0
,通常以 top
是否爲 -1
來斷定是否爲空棧,當定義了棧的最大容量時,則棧頂 top
必須小於最大容量值Java
代碼實現一個順序棧,很是簡單以下:/** * @url: i-code.online * @author: 雲棲簡碼 * @time: 2020/12/8 16:48 */ public class Stack<T> { private Object[] stack; private int stackSize; private int top = -1; public Stack(int size){ stackSize = size; stack = new Object[size]; } public void push(T value){ if (top < stackSize-1){ top++; stack[top] = value; return; } throw new ArrayIndexOutOfBoundsException(top +"越界"); } public T pop(){ if (top > -1){ top--; return (T) stack[top+1]; } throw new ArrayIndexOutOfBoundsException(top +"越界"); } public boolean empty(){ return top == -1; } }
top-1
就能夠了。對於查找操做,棧沒有額外的改變,跟線性表同樣,它也須要遍歷整個棧來完成基於某些條件的數值查找,上述代碼中並未去實現該功能node
top
指針,這是壓棧和出棧操做的重要支持。top
指針。以下圖所示,插入新的數據放在頭部,則須要讓新的結點指向原棧頂,即 top
指針指向的對象,再讓 top
指針指向新的結點。top
指針指向棧頂元素的 next
指針便可完成刪除。對於鏈式棧來講,新增刪除數據元素沒有任何循環操做,其時間複雜度均爲 O(1)
。/** * @url: i-code.online * @author: 雲棲簡碼 * @time: 2020/12/8 20:57 */ public class LinkedList<E> { private Node<E> top = new Node<>(null,null); public void push(E e){ Node<E> node = new Node<>(e,top.next); top.next = node; } public E pop(){ if (top.next == null){ throw new NoSuchElementException(); } final Node<E> next = top.next; top.next = next.next; return next.item; } private static class Node<E>{ E item; Node<E> next; public Node(E item, Node<E> next){ this.item = item; this.next = next; } } }
對於查找操做,相對鏈表而言,鏈棧沒有額外的改變,它也須要遍歷整個棧來完成基於某些條件的數值查找。面試
leetcode
上的案例來練習,以下'(',')','{','}','[',']'
的字符串,判斷字符串是否有效。有效字符串需知足:左括號必須與相同類型的右括號匹配,左括號必須以正確的順序匹配。例如,{ [ ( ) ( ) ] }
是合法的,而{ ( [ ) ] }
是非法的。public boolean isValid(String s) { Stack stack = new Stack(); for(int i =0;i<s.length();i++){ char curr = s.charAt(i); if (isLeft(curr)) { stack.push(curr); }else { if (stack.empty()) return false; if (!isPair(curr,(char)stack.pop())){ return false; } } } if (stack.empty()){ return true; }else { return false; } } public boolean isPair(char curr,char expt){ if ((expt == '[' && curr == ']') || (expt == '{' && curr == '}') || (expt == '(' && curr == ')')) return true; return false; } public boolean isLeft(char c){ if (c == '{' || c == '[' || c == '(') return true; return false; }
O(1)
。而在查找操做中,棧和線性表同樣只能經過全局遍歷的方式進行,也就是須要 O(n)
的時間複雜度本文由AnonyStar 發佈,可轉載但需聲明原文出處。
歡迎關注微信公帳號 :雲棲簡碼 獲取更多優質文章
更多文章關注筆者博客 :雲棲簡碼 i-code.online編程