栈 Stack
栈的基本实现
入栈 出栈 查看栈 栈元素数 栈是否为空
package com.dataStructrue;
public interface Stack<E> {
int getSize();
boolean isEmpty();
void push(E e);
E pop();
E peak();
}
package com.dataStructrue;
public class ArrayStack<E> implements Stack<E> {
Array3<E> array3;
public ArrayStack(int capacity){
array3=new Array3<>(capacity);
}
public ArrayStack(){
array3=new Array3<>();
}
public int getSize(){
return array3.getSize();
}
@Override
public boolean isEmpty(){
return array3.isEmpty();
}
public int getCapacity(){
return array3.getCapacity();
}
@Override
public void push(E e){
array3.addLast(e);
}
@Override
public E pop(){
return array3.removeLast();
}
public E peak(){
return array3.getLast();
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append("Stack:");
res.append('[');
for (int i = 0; i < array3.getSize(); i++) {
res.append(array3.get(i));
if(i!=array3.getSize()-1){
res.append(",");
}
}
res.append("] top");
return res.toString();
}
}
package com.dataStructrue;
public class M {
public static void main(String[] args){
ArrayStack<Integer> stack=new ArrayStack<>();
for (int i = 0; i < 5; i++) {
stack.push(i);
System.out.println(stack);
}
stack.pop();
System.out.println(stack);
}
}
括号匹配
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack=new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c=s.charAt(i);
if(c=='('||c=='['||c=='{')
stack.push(c);
else {
if (stack.isEmpty())
return false;
char topChar=stack.pop();
if(c==')'&&topChar!='('){return false;}
if(c==']'&&topChar!='['){return false;}
if(c=='}'&&topChar!='{'){return false;}
}
}
return stack.isEmpty();
}
}