Java实现一个简单的栈

栈我们可以理解为一个箱子,先放进去的东西在最下面,所以是一个先进后出的原则。下面我们看看一个简单的Demo。

 

package com.tu.test.stack;

 

public class Node {

int data;

Node pre;//previous Node

 

public Node(int data){

this.data = data;

}

}

 

package com.tu.test.stack;

 

public class MyStack {

private Node head;//first node

private Node current;//current node

 

/**

* put into stack

* @param data

*/

public void push(int data){

Node node = new Node(data);

if (head == null) {

head = node;

current = head;

} else {

node.pre = current;//current节点将作为当前节点的前驱动节点

current = node;//让current节点永远指向新添加的那个节点

}

}

 

/**

* out of stack

*/

public Node pop(){

if (current == null){

return null;

}else {

Node node = current;//current是我们要出栈的节点

current = current.pre;//每出栈一个节点,current后退一位

return node;

}

}

}

 

package com.tu.test.stack;

 

public class MyStackTest {

 

public static void main(String[] args) {

MyStack myStack = new MyStack();

for (int i = 1;i<=3;i++) {

myStack.push(i);

}

 

for (int i = 1;i <= 3;i++) {

System.out.println(myStack.pop().data);

}

}

 

}

 

输出结果:

3

2

1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值