1.数组方式
import java.util.Arrays;
class MyStack<E>{
private Object[] stack;
int size;//数组中存储元素的个数
public MyStack() {
stack=new Object[10];//初始长度为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(E item){
ensureCapacity(size+1);//检查容量
stack[size++]=item;
return item;
}
//判断数组容器是否已满,若已满则扩充数组空间
private void ensureCapacity(int size){
int len=stack.length;
if(size>len){//数组已满
int newLen=10;//每次数组扩充的容量
stack=Arrays.copyOf(stack, newLen);
}
}
}
public class Main2 {
public static void main(String[] args) {
MyStack<Integer> s=new MyStack<Integer>();
s.push(1);
s.push(2);
System.out.println("栈中元素个数:"+s.size);
System.out.println("栈顶元素为:"+s.pop());
}
}
2.链表方式
class Node<E>{
Node <E>next=null;
E data;
public Node(E data){
this.data=data;
}
}
public class Stack<E> {
Node<E> top=null;
public boolean isEmpty(){
return top==null;
}
public void push(E data){
Node<E> newNode=new Node<E>(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(this.isEmpty()){
return null;
}
return top.data;
}
public static void main(String[] args) {
Stack<Integer> s=new Stack<Integer>();
s.push(1);
s.push(2);
System.out.println("栈顶元素为:"+s.pop());
}
}