栈——java实现

定义

栈是一种后进先出的数据结构,即Last in first out,故又称LIFO表。栈只在表的一端进行插入(push)和删除(pop)操作,允许插入和删除的一端称为栈顶,

另一端则为栈底。


结构

如下图:



实现

栈的链表实现



使用单链表实现栈,代码如下:


package com.lemon.stack;
/**
 * this class using list realize the stack of data structure
 * @author yanan
 * @param <T>
 */
public class MyStack<T> {
	public static class Node<T>{
		private T value;
		private Node<T> next;
		public Node(T value, Node<T> next) {
			this.value = value;
			this.next = next;
		}
	}
	public MyStack(){
		this.topOfStack=new Node<T>(null, null);
	}
	private int size;
	private Node<T> topOfStack;

	/**
	 * remove an element which is at the top of stack
	 * @return
	 */
	public T pop(){
		T t = topOfStack.value;  
		topOfStack = topOfStack.next;
		size--;
		return t; 

	}

	/**
	 * put the element to the end of stack
	 * @param object
	 */
	public void push(T object){
		Node<T> node=new Node<T>(object,null);
		node.next=topOfStack;
		topOfStack=node;
		size++;
	}
	
	/**
	 * check whether current stack is null or not
	 * @return
	 */
	public boolean isEmpty(){
		return size==0;
	}
	/**
	 * return an element which is at the top of stack
	 * @return
	 */
	public T peek(){
		return topOfStack.value;
	}

	public static void main(String[] args) {
		MyStack<String> stack=new MyStack<String>();
		stack.push("a");
		stack.push("b");
		stack.push("c");
		System.out.println(stack.pop());
		System.out.println(stack.size);
		System.out.println(stack.peek());
	}
}

栈的数组实现


package com.lemon;

/**
 * 栈的数组实现
 * @author andy
 *
 */
public class MyStack<T> {
	private static final int INIT_SIZE=5;
	Object[] data;
	int size=0;
	public MyStack(){
		data=new Object[INIT_SIZE];
	}
	
	public void push(Object obj){
		if(size>data.length){
			throw new ArrayIndexOutOfBoundsException();
		}
		if(size==data.length){
			//当栈满时,其容量扩大两倍.
			Object[] newData=new Object[data.length*2];
			for(int i=0;i<data.length;i++){
				newData[i]=data[i];
			}
			data=newData;
		}
		data[size]=obj;
		size++;
	}
	
	public Object peek(){
		Object obj=data[size-1==0?0:size-1];
		return obj;
	}
	
	public Object pop(){
		int index=size-1==0?0:size-1;
		Object obj=data[index];
		data[index]=null;
		size--;
		return obj;
	}
	
	public boolean isEmpty(){
		return size<=0;
	}
	
	public static void main(String[] args) {
		MyStack<String> stack=new MyStack<String>();
		stack.push("a");
		stack.push("2");
		stack.push("3");
		stack.push("c");
		stack.push("5");
		stack.push("6");
		System.out.println(stack.peek());
		while(!stack.isEmpty()){
			System.out.println(stack.pop());
		}
	}
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值