创建一个名为inverse_Stack的类,在该类中,我们的“堆栈”的组织方式是first /“ bottom”元素位于索引(-1)处。每个推入的元素都放在[当前]最上面的元素之前的阵列插槽中。 if(size = 0)存储在索引:(长度-1); if(size = 1),存储在索引:(length -2); if(size = 2),存储在索引:(length-3);
这是我到目前为止所拥有的。对于反向堆栈,使用push pop peek方法迷路了。我知道如何使它们在常规堆栈中工作
public class Inverse_Stack<T> implements StackADT<T>{
private T[] stack;
private int top;
//private int bot;
public Inverse_Stack(){
this(100);
}
public Inverse_Stack(int capacity){
top = 0;
stack = (T[] new Object[capacity];
}
public int size(){
//returns size of array
return stack.length;
}
public void push(T element){
//fill in code
}
private void expandCapacity(){
T[] newStack = (T[] new Object[stack.length*2];
for(int i = 0; i < stack.length;i++)
newStack[i] = stack[i];
stack = newStack;
}
public T pop(){
if(isEmpty())
throw new RuntimeException("Empty Stack");
//fill in code
}
public T peek(){
if(isEmpty())
throw new RuntimeException("Empty Stack");
//fill in code
}
答案 0 :(得分:0)
length
告诉您容量:堆栈可以容纳的项目数。您还需要保留一个count
变量,以便知道堆栈中当前有多少个项目。
我不会编写Java代码,但是我可以给您大致的想法:
在构造函数中,将count
设置为0。
isEmpty
如果true
大于0,则返回count
。
push
if the stack is full, expand the capacity
add element at stack[count]
increment count
pop
if the stack is empty, throw empty stack exception
decrement count
return the value at stack[count]
peek
类似于pop
,但实际上并没有减少count
。
答案 1 :(得分:0)
不是 ArrayDeque
完全按照自己的意愿做吗?
public class InverseStack<T> extends ArrayDeque<T> {
…
}
和toArray( T[] a )
将获得您的逆数组
答案 2 :(得分:0)
这是我的回答。我觉得这对你更有帮助。
class StackX {
private int maxSize; //size of stack array
private char[] stackData;
private int top; //top of stack
//-------------------------------------------------------------------------
public StackX(int s) {
this.stackData = new char[s];
this.maxSize = s;
this.top = -1;
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public void push(char item) {
if (isFull()) {
System.out.println("Stack is full");
return;
}
stackData[++top] = item;
}
public char pop() throws Exception {
if (isEmpty()) {
throw new Exception("Stack is empty");
}
return stackData[top--];
}
public char peek() throws Exception {
if (isEmpty()) {
throw new Exception("Stack is empty");
}
char peekValue = this.pop();
this.push(peekValue);
return peekValue;
}
public void display() {
if (isEmpty()) {
System.out.println("Stack is empry");
}
System.out.println("Start printing stack data");
for (int i = top; i >= 0; i--) {
System.out.println(stackData[i]);
}
System.out.println("End printing stack data");
}
}