public class Stack {
//定义一个头和一个当前节点
public Node head;
public Node current;
//方法:入栈操作
public void push(int data) {
//如果当前栈为空,则新建一个节点保存数据,新建一个current节点指向当前节点
if(head == null) {
head = new Node(data);
current = head;
} else {
Node nextNode = new Node(data);
nextNode.pre = current; //上一个节点作为新建节点前驱节点
current = nextNode;//前驱节点指向新建节点
}
}
//方法出栈
public Node pop() {
if(current == null) {
return null;
}
//
Node node = current;
//当前节点的前驱节点指向上一个节点的
current = current.pre;
return node;
}
class Node{
int data;
Node pre;
public Node(int data) {
this.data = data;
}
}
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
//输入current节点的数据
System.out.println(stack.pop().data);
System.out.println(stack.pop().data);
System.out.println(stack.pop().data);
}
}
算法---栈(java实现)
最新推荐文章于 2023-01-05 18:14:17 发布