java拾遗录4
一、用数组实现栈操作
废话不说,直接上代码
package stack;
/**
*@作者 qy
*@时间版本 版本1 下午08:49:07 2011-8-30
*/
public class StackTestByArray
{
private Object[] array;
private int top;
public StackTestByArray(int size)
{
array = new Object[size];
top = -1;
}
//判断栈是否为空
public boolean isEmpty()
{
return top == -1;
}
//判断栈是否满
public boolean isFull()
{
return size() == array.length;
}
//返回当前栈的大小
public int size()
{
return top+1;
}
//弹栈
public Object pop()
{
if (isEmpty())
{
System.out.println("栈为空");
return null;
}
Object temp = array[top];
array[top] = null;
top -= 1;
return temp;
}
public void push(Object newValue)
{
if (newValue == null)
{
System.out.println("入栈数据为null");
return;
}
if (isFull())
{
System.out.println("栈满");
return;
}
top++;
array[top] = newValue;
}
//取栈头元素
public Object peek()
{
if (isEmpty())
{
System.out.println("栈为空");
return null;
}
return array[top];
}
}
这是使用数组实现的栈,很简单。
下面是链表实现:(Node类看我前面的文章即可)
package stack;
import array.Node;
/**
*@作者 qy
*@时间版本 版本1 下午09:15:56 2011-8-30
*/
public class StackTestByNode
{
private Node top ;
private int count;
public StackTestByNode()
{
top = null;
count = 0;
}
//是否栈满
public boolean isFull()
{
//这里我们用的链表 姑且没有满的状态 内存爆了再说
return false;
}
//是否栈空
public boolean isEmpty()
{
return count == 0;
}
//大小
public int size()
{
return count;
}
//入栈
public void push(Object value)
{
if (value == null)
{
System.out.println("插入数据为null");
return ;
}
count++;
Node n = new Node(value, top);
top = n;
}
//出栈
public Object pop()
{
if (isEmpty())
{
System.out.println("栈空");
return null;
}
count--;
Object value = top.value;
top = top.next;
return value;
}
//取栈顶元素
public Object peek()
{
if (isEmpty())
{
System.out.println("栈空");
return null;
}
return top.value;
}
}
也是很简单,就不多说了,大家看看就好,不要出声.........