定义
栈是一种后进先出的数据结构,即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());
}
}
}