package shuju_arguments;
/***
* 下压栈,使用链表的数据结构来实现
* **/
class node<T>{
//链表中存入的数据
public T items;
//链表中存的下一个元素的位置
public node nest;
}
public class push_stack {
//栈中的数量
private int nums;
//栈顶元素
private node first;
//向栈中添加元素
public void push(Object o){
node oldNode = first;
node<Integer> node = new node<Integer>();
node.items = (Integer)o;
first = node;
node.nest = oldNode;
nums++;
}
//从栈中弹出栈顶元素
public int pop(){
node<Integer> oldNode = first;
first = oldNode.nest;
int num = oldNode.items;
oldNode = null;
nums--;
return num;
}
//遍历栈中的元素
public void interator(){
for(node node = first;node!=null;node = node.nest){
System.out.println(node.items);
}
}
public static void main(String[] args) {
push_stack push_stack = new push_stack();
push_stack.push(1);
push_stack.push(2);
push_stack.push(3);
push_stack.push(4);
System.out.println("元素有:");
push_stack.interator();
int a = push_stack.pop();
int b = push_stack.pop();
int c = push_stack.pop();
System.out.println("元素有:");
push_stack.interator();
// System.out.println(a);
// System.out.println(b);
// System.out.println(c);
// System.out.println(push_stack.nums);
}
}
使用链表来模拟栈(java实现)
最新推荐文章于 2022-11-27 22:45:55 发布