采用数组和节点方式实现的堆栈

基于数组方式的栈的实现:

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;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值