这是我所在的一个班的编程作业,不希望你帮我解决,帮我理解一下。我还要说,教授对程序的外观非常严格,所以请不要给我一个改变任何名称的解决方案(除非它们应该被保留。)另外,我们没有涵盖堆栈,弹出() 或 push(),所以我向前看了 4 章,以了解他在寻找什么。
这是他给我们的密码。
public class SimpleStack {
char[] data;//this array holds that stack
int tos; //index of top of stack
//Construct an empty stack given it's size.
public SimpleStack(int size){
data = new char[size];
tos = 0;
}
public void push(char ch){
if(isFull()){
System.out.println("--Stack is full.");
return;
}
data[tos] = ch;
tos++;
}
public char pop(){
if(isEmpty()){
System.out.println("--Stack is empty.");
return (char)0;
}
tos--;
return data[tos];
}
public isEmpty(){
boolean empty(tos = 0);
}
public isFull(){
}
}
我应该完成底部的两个布尔语句,我知道如何做到这一点。另外我应该创建调用 SimpleStack 的 main 方法,并输入 AJ 作为十个字符的测试,然后让它给我相反的结果。我没有被告知我应该如何构建 main,但教授也没有说我需要获取用户输入。所以我可以创建一个已经从 AJ 填充的数组。
我使用此代码测试了我的主要内容。我可以要求用户给我起始字母“A”,然后创建一个循环以在“K”之前结束它,我还测试了如何将数组的大小发送到 SimpleStack。
import javax.swing.*;
public class SimpleStackDemo {
public static void main(String[] args) {
char c[] = "ABCDEFGHIJ".toCharArray();
int aryL = c.length;
SimpleStack sS1 = new SimpleStack(aryL);
//System.out.println("The Array is, " + aryL);
//SimpleStack sS1 = new SimpleStack(//something);
}
}
我想我想做的是询问用户数组应该有多大,使用它来调用 SimpleStack,然后询问他们想要从哪个字母开始,然后将其放入 tos?
所以,isFull
很容易做到。为什么?实例化您的 时SimpleStack
,用户必须指定堆栈的大小,该大小用于创建data
. 你知道你在什么索引上,tos
. 您所要做的就是检查是否tos
是最后一个索引:
return (tos == data.length - 1);
isEmpty
遵循相同的想法。tos
是您当前的索引。您所要做的就是检查您当前的索引是否为 0:
return (tos == 0);
注意事项:
当您push()
或 时pop()
,您的tos
增加或减少,跟踪您的索引。因为您知道自己在堆栈中的位置,所以您始终可以相对于绝对值来判断您是否位于堆栈的任一端。
在您的主要课程中:
public static void main(String[] args) {
char c[] = "ABCDEFGHIJ".toCharArray();
int aryL = c.length;
SimpleStack sS1 = new SimpleStack(aryL); // You have a stack with size 10;
System.out.println(sS1.isEmpty()); // on index 0, will return true.
sS1.push('A'); // Adds A to top of empty stack, tos = 1 after this line
sS1.push('B'); // Adds B to top of empty stack, tos = 2 after this line
sS1.push('C'); // Adds C to top of empty stack, tos = 3 after this line
sS1.pop(); // Removes top of empty stack, tos = 2 after this line
sS1.push('C'); // Adds C to top of empty stack, tos = 3 after this line
// Stack now looks like:
// C
// B
// A -> bottom of stack
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句