/**
* Author:Dang Yibo
*
* @DATA: 2021/7/22
* @TIME: 14:40
* @Description
*/
public class LStack {
LNode header; //栈顶元素
int elementCount;// 栈内元素个数
int size;// 栈的大小
/**
* 构造函数,构造一个空的堆栈
*/
public LStack()
{
header = null;
elementCount = 0;
size = 0;
}
/**
* 通过构造器 自定义栈的大小
size 栈的大小
*/
public LStack(int size)
{
header = null;
elementCount = 0;
this.size = size;
}
/**
* 设置堆栈大小
* size 堆栈大小
*/
public void setSize(int size)
{
this.size = size;
}
/**
* 设置栈顶元素
* header 栈顶元素
*/
public void setHeader(LNode header)
{
this.header = header;
}
/**
* 获取堆栈长度
* 堆栈长度
*/
public int getSize()
{
return size;
}
/**
* 返回栈中元素的个数
* 栈中元素的个数
*/
public int getElementCount()
{
return elementCount;
}
/**
* 判断栈是否为空
* @return 如果栈是空的,返回真,否则,返回假
*/
public boolean isEmpty()
{
if (elementCount == 0)
return true;
return false;
}
/**
* 判断栈满
* 如果栈是满的,返回真,否则,返回假
*/
public boolean isFull()
{
if (elementCount == size)
return true;
return false;
}
/**
* 把对象入栈
* value 对象
*/
public void push(Object value)
{
if (this.isFull())
{
throw new RuntimeException("栈已满");
}
header = new LNode(value, header);
elementCount++;
}
/**
* 出栈,并返回被出栈的元素
* 被出栈的元素
*/
public Object pop()
{
if (this.isEmpty())
{
throw new RuntimeException("栈为空");
}
Object obj = header.getElement();
header = header.getNext();
elementCount--;
return obj;
}
/**
* 返回栈顶元素
* 栈顶元素
*/
public Object peek()
{
if (this.isEmpty())
{
throw new RuntimeException("栈为空");
}
return header.getElement();
}
public static void main ( String[] args ) {
LStack lStack = new LStack(100);
lStack.push("java");
lStack.push("我爱java");
lStack.push("你好");
lStack.push(" 1 ");
System.out.println("——————————————————出栈顺序———————————————————");
System.out.println(lStack.pop());
System.out.println(lStack.pop());
System.out.println(lStack.pop());
System.out.println(lStack.pop());
}
}
测试结果如下:用链表实现栈的先进后出,后进先出