Java实现栈
程序员文章站
2022-03-30 08:24:22
...
栈的定义
栈(stack)是限定在表尾进行插入和删除操作的线性表.
栈顶和栈底:允许插入和删除的一端为栈顶(Top),相对另一端为栈底(Buttom).
空栈:不含任何数据的栈称为空栈.
栈又称为先进后出(LIFO)的线性表
栈的操作
入栈:插入元素;
出栈:获取元素并移除
Java实现栈
定义节点
节点包括数据和指向下一个节点的引用
class Node{
public Integer data;
public Node next;
public Node(Integer data) {
super();
this.data = data;
}
}
定义栈
分别为指向栈顶元素的引用和栈的长度.
class Stack{
private Node top;
private Integer size = 0;
}
获取栈顶元素
public Integer getTop(){
return top.data;
}
pop元素
获取并删除栈顶元素
public Integer pop() {
if(top == null) {
return null;
}
else {
Node n = top;
top = n.next;
Integer data = n.data;
n = null;
return data;
}
}
push元素
public void push(Integer data) {
Node n = new Node(data);
if(top == null) {
top = n;
}
else {
n.next = top;
top = n;
}
size++;
}
清空栈
public void clean() {
while(top != null ) {
Node n = top;
top = n.next;
n = null;
}
size = 0;
}
转化为String
public String toString() {
String str = "The stack data is :";
Node n = top;
while(n != null) {
str += n.data + " ";
n = n.next;
}
return str;
}
测试
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack stack = new Stack();
stack.push(5);
stack.push(10);
stack.push(15);
stack.push(25);
System.out.println(stack.toString());
System.out.println("Top data :" + stack.getTop());
System.out.println("The size is :" + stack.getSize());
System.out.println("pop a data");
stack.pop();
System.out.println(stack.toString());
System.out.println("clean the stack");
stack.clean();
System.out.println(stack.toString());
}
输出
The stack data is :25 15 10 5
Top data :25
The size is :4
pop a data
The stack data is :15 10 5
clean the stack
The stack data is :