1. 程式人生 > >java-模擬存放String型別資料的棧

java-模擬存放String型別資料的棧


package com.sc;
/**
 * 
 * 用來模擬一個存放String資料的棧
 */
class Node{
    private String str;

    public Node(){}
    public Node(String str){
        this.str=str;
    }

    public String getstr(){
        return this.str;
    }

}
class Stack1{
    private Node node []=new Node[20];
    private int size;
    //建構函式初始化
public Stack1(){ this.size=0; } public void push(Node no){ if(getSize()>=node.length){ //進行擴容 Node node_new[]=new Node[node.length*2]; System.arraycopy(node, 0, node_new, 0, node.length); node=node_new; } node[size++]=no; } public
String pop(){ if(size<=0)return null; else return node[--size].getstr(); } public int getSize(){ return this.size; } } public class stackOfString { public static void main(String[] args) { // TODO Auto-generated method stub Node node=new
Node("zhangsan"); Stack1 st=new Stack1(); st.push(node); System.out.println(st.pop()); System.out.println(st.pop()); } }