Topic: 新手求字符串的堆棧問題!

  Print this page

1.新手求字符串的堆棧問題! Copy to clipboard
Posted by: sealsealseal
Posted on: 2006-03-24 09:24

使用StringBuffer类,構建字符堆棧
public class CharStack{
private StringBuffer stack;
public CharStack(){
stack =new StringBuffer();
}
public CharStack(int capacity){
stack=new StringBuffer(capacity);
}
public void push(char c){
//插入代碼
}
public int pop(){
//插入代碼
}
public char[] list(){
//插入代碼
}
public String toString(){
//插入代碼
}
}

2.Re:新手求字符串的堆棧問題! [Re: sealsealseal] Copy to clipboard
Posted by: suntao19830709
Posted on: 2006-03-24 11:28


/**
* 字符栈
* @author sunt
*/
public class CharStack {
/**
* 本栈对应的stringBuffer
*/
private StringBuffer stack = null;

/**
* 栈的容量
*/
private int size = 0;

/**
* 构造函数
*/
public CharStack(){
//缺省栈的容量为256
this.stack =new StringBuffer(256);
this.size=256;
}
/**
* 构造函数
* @param size
*/
public CharStack(int size){
if (size <= 0) {
throw new RuntimeException("The size must over zero!");
}
this.stack = new StringBuffer(size);
this.size=size;
}

/**
* 入栈
*/
public void push(char c){
if (!isFull()) {
stack.append(c);
} else {
throw new RuntimeException("The stack is full!");
}
}
/**
* 出栈
*/
public char pop(){
if (!isEmpty()) {
char c = stack.charAt(stack.length() - 1);
stack = stack.delete(stack.length() - 1,
stack.length());
return c;
} else {
throw new RuntimeException("The stack is empty!");
}
}
/**
* 获得栈的所有字符成员
* @return
*/
public char[] list(){
char[] cha = new char[stack.length()];
for(int i = 0;i<stack.length();i++){
cha[i]= stack.charAt(i);
}
return cha;
}
/**
* 转化为字符串
*/
public String toString(){
return stack.toString();
}

/**
* 判断栈是否为空
*/
private boolean isEmpty() {
return this.stack.length() == 0 ? true : false;
}

/**
* 判断栈是否已满
*/
private boolean isFull() {
return this.stack.length() == this.size ? true : false;
}
}

3.Re:新手求字符串的堆棧問題! [Re: sealsealseal] Copy to clipboard
Posted by: sealsealseal
Posted on: 2006-03-24 12:00

謝謝指教~


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923