package com.java.datastructure.stact; //java两栈共享空间 public class ShareLinearStact { private final static int defSize = 2; private int top1 = -1; private int top2 = defSize; private String[] data = new String [defSize]; //添加元素 public boolean push(String pData, int type) { //判断是否栈满 if(top1+1 ==top2) { System.out.println("栈满了。。。"); return false; } // if(type==1) { top1++; data[top1] = pData; } else if (type==2) { top2 --; data[top2] = pData; } return true; } //取出元素 public String pop(int type) { //判断是否栈满 if(isEmpt()) { return null; } String temp = null; if(type==1) { temp = data[top1]; data[top1] = null; top1--; } else if (type==2) { temp = data[top2]; data[top2] = null; top2++; } return temp; } //删除元素 public boolean del(int type) { if(isEmpt()) { return false; } if(type==1) { data[top1] = null; top1--; } else if (type==2) { data[top2] = null; top1++; } return true; } //获取栈顶元素 public String peek1() { if(top1==-1) { return null; } else { return data[top1]; } } //获取栈顶元素 public String peek2() { if(top2==defSize) { return null; } else { return data[top2]; } } // //查找元素 // public int search(String content) { // int index = -1; // for (int i=0; i<length(); i++) { // if(data[i].equals(content)) { // index = i; // break; // } // } // return index; // } public void resize() { String[] dataTemp = new String [data.length*2]; for (int i=0; i<data.length; i++) { dataTemp [i] = data[i]; data[i] = null; } data = dataTemp; dataTemp = null; } //判断是否为空 public boolean isEmpt() { return top1==-1 && top2==defSize; } //获取栈 实际元素个数 public int length() { //top1栈元素 Integer t1 = top1+1; Integer t2 = defSize-top2; return t1+t2; } //清除 public void clean() { for (int i=0; i<data.length; i++) { data[i] = null; } top1 = -1; top2 = defSize; } public void display() { for (int i=0; i<data.length; i++) { System.out.println("打印每个元素"+data[i]); } } public static void main(String[] args) { ShareLinearStact stact = new ShareLinearStact(); String content = "isNull "; System.out.println(content+"判断是否为空 "+stact.isEmpt()); System.out.println(content+"获取栈顶元素 "+stact.pop(1)); System.out.println(content+"获取元素个数 "+stact.length()); System.out.println(content+"获取栈顶-peak元素 "+stact.peek1()); //System.out.println(content+"获取查找stactA元素 "+stact.search("stactA")); stact.push("stactA",1); stact.push("stactB",1); stact.push("stactC",2); //打印 stact.display(); content = "notNull "; System.out.println(content+"判断是否为空 "+stact.isEmpt()); System.out.println(content+"获取元素个数 "+stact.length()); System.out.println(content+"获取栈顶-peak1-元素 "+stact.peek1()); System.out.println(content+"获取栈顶-peak2-元素 "+stact.peek2()); } }
4 java两栈共享空间
最新推荐文章于 2021-03-21 06:56:49 发布