# 顺序栈与链式栈的图解与实现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
就能够了。对于查找操做,栈没有额外的改变,跟线性表同样,它也须要遍历整个栈来完成基于某些条件的数值查找,上述代码中并未去实现该功能
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