配列とノード方式で実装されたスタック
配列ベースのスタックの実装:
ノードベーススタックの実装
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;
}
}