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

猜你喜欢

转载自williamwhj.iteye.com/blog/2322247