数据结构 栈 java实现

1.内部用数组实现
/**
 * 栈,数组实现
 * @author 年糕
 *
 */
public class MyStack<E> {
	private Object[]data=null;
	private int size;//栈大小
	private int top=-1;//栈顶
	public MyStack() {
		size=10;
		data=new Object[size];//默认容量为10
	}
	public MyStack(int size) {
		
		this.size = size;
		data=new Object[this.size];//有参构造函数,开辟数组
	}
	/**
	 * 进栈
	 */
	
	public void push(Object o) {
		if(top==size-1) {
			throw new RuntimeException("栈已满,无法将元素入栈!"); 
		}else {
		data[++top]=o;
		size++;
		}
	}
	/**
	 * 出栈
	 */
	
	public E pop() {
		if(top==-1) {
			throw new RuntimeException("栈已空,无法将元素出栈!"); 
		}else {
			size--;
			return (E)data[top--];
		}
	}
	/**
	 * 获取栈顶元素,不出栈
	 */
	
	public E peek() {
		if(top==-1) {
			throw new RuntimeException("栈空");
			
		}else {
			return (E) data[top];
		}
	}
	
	/**
	 * 栈大小
	 */
	
	public int getSize() {
		return this.top+1;
	}
	/**
	 * 判断是否为空
	 * @return
	 */
	public boolean isEmpty() {
		if(this.getSize()==0) {
			return true;
		}else {
			return false;
		}
	}
	
	
	
	
}	

2.内部用结点实现,链栈


public class MyLinkStack<E> {
    private class Node{
    	E e;
    	Node next;
		public Node() {
			
		}
		public Node(E e, MyLinkStack<E>.Node next) {
			this.e = e;
			this.next = next;
		}
		
    }
    
    
    public MyLinkStack() {
		this.top=null;
		this.size=0;
	}


	private Node top;//栈顶元素
    private int size;//栈大小
    
    
    /**
     * 判断栈空
     */
    public boolean isEmpty() {
    	return size==0;
    }
    /**
     * 栈大小
     */
    public int getSize() {
    	return this.size;
    }
    /**
     * 入栈
     */
    public void push(E e) {
    	top=new Node(e,top);
    	size++;
    }
    /**
     * 出栈
     */
    public E pop() {
    	if(size==0) {
    		System.out.println("空");
    		return null;
    	}else {
    	E e=top.e;
    	top=top.next;
    	size--;
    	return e;
    }}
    /**
     * 获取栈顶元素,不出
     */
    
    public E peek() {
    	
        	if(size==0) {
        		System.out.println("空");
        		return null;
        	}else {
        	
        	return top.e;
    }
    
    
}
    
}


猜你喜欢

转载自blog.csdn.net/qq_39147516/article/details/79242338