面试手撕代码总结(三)-栈

面试手撕代码总结(三)-栈

1.使用数组实现栈

public class MyStack{
  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{
	Node next=null;
	E data;
	public Node(E data){this.data=data;}
}
public class Stack{
	 Node top=null;
	 public boolean isEmpty(){
		return top==null;
	 }
	 public void push(E data){
		Node newNode=new Node(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 stackData;
   private Stack stackMin;
   public MyStack(){
      this.stackData=new Stack();
	  this.stackMin=new Stack();
	}
   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{
   private Stack s1=new Stack();
   private Stack s2=new Stack();
   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 stack=new Stack<>();
  int index=0;
  for(int i=0;i

你可能感兴趣的:(java核心技术)