面试手撕代码总结(三)-栈
1.使用数组实现栈
public class MyStack<E>{
private Object[] stack;
private int size;
public MyStack(){
stack=new Object[10];
}
//判断栈是否为空
public boolean isEmpty(){
return size==0;
}
public E peek(){
if(isEmpty()){
return null;
}
return(E) stack[size-1];
}
public E pop(){
E e=peek();
stack[size-1]=null;
size--;
return e;
}
public E push(){
ensureCapacity(size+1);
stack[size+1]=item;
return item;
}
//判断数组器是否已满,若已满,则扩充数组空间
private void ensureCapacity(int size){
int len=stack.length;
if(size>len){
int newLen=10;
stack=Arrays.copyOf(stack,newLen);
}
}
}
2.使用链表的方式实现栈
class Node<E>{
Node<E> next=null;
E data;
public Node(E data){this.data=data;}
}
public class Stack<E>{
Node<E> top=null;
public boolean isEmpty(){
return top==null;
}
public void push(E data){
Node<E> newNode=new Node<E>(data);
newNode.next=top;
top=newNode;
}
public E pop(){
if(this.isEmpty())
return null;
E data=top.data;
top=top.next;
return data;
}
public E peek(){
if(isEmpty){
return null;
}
return top.data;
}
}
3.求栈中最小元素
public class MyStack{
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack(){
this.stackData=new Stack<Integer>();
this.stackMin=new Stack<Integer>();
}
public void push(int newNum){
if(this.stackMin.isEmpty){
this.stackMin.push(newNum);
}else if(newNum<=this.getMin()){
this.stackMin.push(newNum);
}
this.stackData.push(newNum);
}
public int pop(){
if(this.stackData.isEmpty){
throw new RuntimeException("Your stack is empty");
}
int value=this.stackData.pop();
if(value==this.getMin()){
this.stackMin.pop();
}
return value;
}
public int getMin(){
if(this.stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty");
}
return this.stackMin.peek();
}
}
4.两个栈模拟队列
public class MyQueue<E>{
private Stack<E> s1=new Stack<E>();
private Stack<E> s2=new Stack<E>();
public sychronized void put(E e){
s1.push(e);
}
public sychronized void pop(){
if(s2.isEmpty()){
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
return s2.pop();
}
public sychronized boolean empty(){
return s1.isEmpty()&&s2.isEmpty();
}
}
5.判断一个栈是否是另一个栈的弹出顺序
public boolean IsPopOrder(int[] pushA,int[] popA){
if(pushA==null||popA==null){
return false;
}
Stack<Integer> stack=new Stack<>();
int index=0;
for(int i=0;i<pushA.length;i++){
stack.push(pushA[i]);
while(!stack.isEmpty()&&stack.peek()==popA[index]){
stack.pop();
index++;
}
}
return stack.isEmpty();
}