public class ReverseString {
Stack word;
Stack sentence;
public void reverse(String sentence){
for(int i=0; i<sentence.length(); i++){
char n =sentence.charAt(i);
if(n!=' '){
word.push(n);
}else{
while(!word.empty()){
this.sentence.push(word.pop());
}
this.sentence.push(' ');
}
}
}
public void show(){
while(!this.sentence.empty()){
System.out.println(this.sentence.pop());
}
}
public static void main(String[] args) {
new ReverseString().reverse("the sky is blue");
}
}
想不明白为何在执行word.push(n)
时 会报 java.lang.NullPointerException
栈是后进先出,只要记住这一点,就不难实现。下面是我的实现:
/**
* StackByArray:数组方式实现栈,实现栈的初始化,入栈出栈操作
*
* @author zeng.xiangdong 1770534116@qq.com
* @version V1.0 2014-8-24 下午10:00:03
*/
public class StackByArray {
// 栈的长度
private int length;
// 栈
private Object[] array;
// 栈顶的下标
private int topIndex = -1;
/**
* StackByArry:构造方法
*
* @param length 初始化栈的长度
*/
public StackByArray(int length) {
this.length = length;
array = new Object[length];
}
/**
* push:入栈
*
* @param obj
* @throws Exception
*/
private void push(Object obj) throws Exception {
if(isFullStack()) {
throw new Exception("栈已满");
}
array[++topIndex] = obj;
}
/**
* offer: 出栈,取出栈顶元素
*
* @return obj
* @throws Exception
*/
private Object offer() throws Exception {
if(isEmptyStack()) {
throw new Exception("栈已空");
}
Object topObject = array[topIndex];
array[topIndex] = null;
topIndex--;
return topObject;
}
/**
* isEmptyStack:判断栈是否为空
*
* @return
*/
private boolean isEmptyStack() {
return (topIndex == -1);
}
/**
* isFullStack:判断栈是否已满
*
* @return
*/
private boolean isFullStack() {
return topIndex == (length - 1);
}
/**
* getLength:取得栈内的数据长度
*
* @return length
*/
private int getLength() {
return topIndex + 1;
}
/**
* outPut:栈内容输出
*/
private void outPut() {
for(Object obj : array) {
if(obj != null) {
System.out.print(obj + ", ");
}
}
System.out.println();
}
/**
* main:(这里用一句话描述这个方法的作用)
*
* @param args
*/
public static void main(String[] args) throws Exception {
StackByArray stack = new StackByArray(10);
for(int i = 1; i <= 8; i++) {
stack.push(i);
stack.outPut();
}
System.out.println("---------------");
System.out.println(stack.offer());
stack.outPut();
System.out.println("---------------");
System.out.println(stack.offer());
stack.outPut();
System.out.println(stack.getLength());
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。