java自定义栈的使用(push与pop操作)
1.Node类的创建
/*
* 定义一个链表
* */
public class Node {
public int date;
public Node next;
public Node() {
}
public Node(int date) {
this.date = date;
}
public Node(int date, Node next) {
this.date = date;
this.next = next;
}
}
2.Stack类的创建
public class Stack {
public Node topStack;
public Node bottomStack;
public Stack() {
}
public Stack(Node topStack, Node bottomStack) {
this.topStack = topStack;
this.bottomStack = bottomStack;
}
public void push(int data){
if(topStack == null){
//栈为空,将数据存入头结点
topStack = new Node(data);
//栈尾与头结点在一块内存
bottomStack = topStack;
}else{
//当栈不为空时
Node node =new Node(data);
//插入的节点指向栈尾
node.next=bottomStack;
//插入的节点成为栈尾
bottomStack= node;
}
}
public void pop (){
//当栈不为空时
if(bottomStack !=null){
Node node = bottomStack;
bottomStack=bottomStack.next;
System.out.println(node.date);
}else{
System.out.println("栈空了");
}
}
}
3.Stack_Test类的创建
public class Stack_Test {
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
}
}
4.测试截图