赞
踩
话不多说,直接上代码:
定义一个通用的接口:
public interface MyStack <T>
{
boolean isEmpty(); //判断是否为空
int getLength(); //获得长度
void clear(); //清空
T pop();
boolean push(T data);
}
一、数组实现栈:
public class MyArrStack<T> implements MyStack<T>
{
private Object[] objs = new Object[5];
private int size = 0;
@Override
public boolean isEmpty()
{
// TODO Auto-generated method stub
return size==0;
}
@Override
public int getLength()
{
// TODO Auto-generated method stub
return size;
}
@Override
public void clear()
{
// TODO Auto-generated method stub
for(int i=0;i<size;i++)
{
objs[i]=null;
}
size=0;
}
@Override
public T pop()
{
// TODO Auto-generated method stub
if(size==0)
{
return null;
}
else
return (T)objs[--size];
}
@Override
public boolean push(T data)
{
// TODO Auto-generated method stub
if(size>=objs.length)
{
//System.out.println("数组已满");
Object[] tmp=new Object[objs.length*3/2+1];
for(int i=0;i<size;i++)
{
tmp[i]=objs[i];
objs[i]=null;
}
objs=tmp;
}
objs[size++]=data;
return true;
}
public static void main(String[] args)
{
MyStack<Integer> st = new MyArrStack<Integer>();
int[] num={1,2,3,5,8,9,6};
for(int i=0;i<num.length;i++)
{
st.push(num[i]);
}
System.out.println("栈中有"+st.getLength()+"个数");
while(!st.isEmpty())
{
System.out.println(st.pop());
}
}
}
二、链表实现栈:
public class MyLinkedStack<T> implements MyStack<T>
{
private Node top;
private int size;
public MyLinkedStack()
{
top=null;
size=0;
}
@Override
public boolean isEmpty()
{
// TODO Auto-generated method stub
return size==0;
}
@Override
public int getLength()
{
// TODO Auto-generated method stub
return size;
}
@Override
public void clear()
{
// TODO Auto-generated method stub
top=null;
size=0;
}
@Override
public T pop()
{
// TODO Auto-generated method stub
if (top != null) {
Node node = top;
// 改变栈顶指针
top = top.pre;
size--;
return node.data;
}
return null;
}
@Override
public boolean push(T data)
{
// TODO Auto-generated method stub
Node node=new Node();
node.data=data;
node.pre=top;
top=node;
size++;
return true;
}
private final class Node
{
private Node pre;
private T data;
}
public static void main(String[] args)
{
int[] num={5,2,1,7,9,6,3};
MyStack<Integer> st=new MyLinkedStack<Integer>();
for(int i=0;i<num.length;i++)
{
st.push(num[i]);
}
System.out.println("栈的长度为:"+st.getLength());
while(!st.isEmpty())
{
System.out.println(st.pop());
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。