基于数组方式的栈的实现:
package com.study.link;
public class ArrayStack {
private Node[] objectArray;
private int topIndex;
public ArrayStack(int length){
objectArray = new Node[length];
}
public Node pop(){
if(topIndex>0){
Node node = objectArray[topIndex-1];
topIndex--;
return node;
}else{
return null;
}
}
public void push(Node node){
topIndex++;
objectArray[topIndex-1]=node;
}
public Node[] getObjectArray() {
return objectArray;
}
public void setObjectArray(Node[] objectArray) {
this.objectArray = objectArray;
}
public int getTopIndex() {
return topIndex;
}
public void setTopIndex(int topIndex) {
this.topIndex = topIndex;
}
public static void main(String[] args) {
ArrayStack stack=new ArrayStack(100);
stack.push(new Node(1));
stack.push(new Node(2));
stack.push(new Node(3));
stack.push(new Node(4));
stack.push(new Node(5));
while(stack.getTopIndex()>0)
{
System.out.println(stack.pop().getValue());
}
}
}
基于节点方式栈的实现
package com.study.link;
/**
* 基于节点方式实现的栈
* 先进后出
* @author Administrator
*
*/
public class NodeStack {
private Node top;//栈顶元素
public Node pop(){
if(top!=null){
Object value = top.getValue();
Node temp = new Node(value);
top = top.getNext();
return temp;
}else{
return null;
}
}
public void push(Node node){
if(node!=null){
node.setNext(top);
top = node;
}else{
top = node;
}
}
public static void main(String[] args) {
NodeStack stack=new NodeStack();
stack.push(new Node(1));
stack.push(new Node(2));
stack.push(new Node(3));
stack.push(new Node(4));
while(stack.top!=null)
{
System.out.println(stack.pop().getValue());
}
}
}
节点:
package com.study.link;
/**
* 链表节点
* 每个链表都有本身值和指向下一个节点的链接
* @author Administrator
*
*/
public class Node {
private Object value;
private Node next;
public Node(Object value){
this.value = value;
next = null;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}