栈在java中的实现

1栈的数组实现

public class ArrayStack
    
    
     
      {
	
	Object[] stack = null;
	private int size;
	
	void initStack(){
		if(stack==null){
			stack = new Object[10];
			size = 0;
		}
	}
	//判断栈是否为空,栈的起始位置为1
	boolean isEmpty(){
		if(size <= 0)
			return true;
		else
			return false;
	}
	//进行入栈操作
	T push(T obj){
		ensureCapacity(size+1);
		stack[++size] = obj;
		return obj;
	}
	//进行出栈
	T pop(){
		if(size>=0){
			return (T) stack[size--];
		}
	 	return null;
	}
	//确认栈的客容量大小,如果超过栈的客容量则扩充,固定的扩充大小为10
	private void ensureCapacity(int len){
		if(len>=this.stack.length){
			System.out.println("容量太小,现在扩充");
			stack = Arrays.copyOf(stack, stack.length+10);
			System.out.println("现在栈的可容量大小为:"+stack.length);
		}
		
	}
	public static void main(String[] args) {
		ArrayStack
     
     
      
       stack = new ArrayStack
      
      
       
       ();
		stack.initStack();
		System.out.println(stack.stack.length);
		
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);
		stack.push(6);
		stack.push(7);
		stack.push(8);
		stack.push(9);
		stack.push(10);
		stack.push(11);
		stack.push(12);
		stack.push(13);
		stack.push(14);
		stack.push(15);
		stack.push(16);
		stack.push(17);
		stack.push(18);
		stack.push(19);
		stack.push(20);
		stack.push(21);
		stack.push(22);
		stack.push(23);
		stack.push(24);
					
		while(!stack.isEmpty()){
			System.out.println(stack.pop());
		}
		
	}

}
      
      
     
     
    
    


2栈的链表实现
public class LinkStack
    
    
     
      {
	Node
     
     
      
       top;
	public LinkStack() {
		// TODO Auto-generated constructor stub
		top = null;
	}
	void push(T data){
		Node
      
      
       
        newNode = new Node
       
       
        
        (data);
		newNode.next = top;
		top = newNode;
	}
	T pop(){
		if(!isEmpty()){
			Node
        
        
          popData = top; top = top.next; return popData.data; }else{ return null; } } boolean isEmpty(){ if(top==null){ return true; }else return false; } public static void main(String[] args) { LinkStack 
         
           stack = new LinkStack 
          
            (); stack.push(1); stack.push(11); stack.push(111); stack.push(1111); stack.push(11111); stack.push(111111); stack.push(1111111); stack.push(11111111); while(!stack.isEmpty()){ System.out.println(stack.pop()); } } } class Node 
           
             { E data; Node 
            
              next = null; public Node() { } Node(E data){ this.data = data; } } 
             
            
           
          
        
       
       
      
      
     
     
    
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值