ich für Computing mit Stapeln ein Programm schreibe ich habe einen Code geschrieben und hier sind die Variable I in sie verwendet haben:schreiben Compute Spanne mit Stapeln in Java
Ein Array von 52 ganzen Zahlen genannt X: Diese ist das Array, das wir seine Spannen berechnen möchten; In diesem Code werden X Elemente durch Zufallsfunktion initialisiert;
Die Ausgabe dieses Programms ist ein Integer-Array namens S, das in der gleichen Größe wie X ist; und S [i] ist die Spannweite der Aktie am Tag i
st ist ein Stapel.
hier So ist der Code, den ich auf der Grundlage des Algorithmus geschrieben haben:
public class ComputingSpansInStack {
static int [] X = new int[52];
static int [] S = new int[52];
public static void SetX()
{
Random rn = new Random();
for (int i = 0; i < 52; i++) {
X[i] = 1 + rn.nextInt(100);
}
}
public static void main(String[] args) {
SetX();
int h;
Stack<Integer> st=new MyStack<>();
boolean done;
for (int i = 0; i<52 ; i++)
{
done = false;
while(!(st.isEmpty()||done))
{
if(X[i]>= X[st.top()])
st.pop();
else
done = true;
}
if(st.isEmpty())
h = -1;
else
h = st.top();
S[i] = i - h;
st.push(i);
}
for (int i =0; i<52; i++)
{
System.out.println(X[i] + " "+ S[i]);
}
}
aber die Ausgabe ist hier:
38 --- 1
7 --- --- 1
16 ----- 2
62 ------ 4
35 ----- 1
31 ----- 1
6 ----- 1 .......
Problem: für 62 Es sollte 3 nicht 4;
hier ist MyStack:
public class MyStack<E> implements Stack<E>{
private final E s[];
int t=0;
public MyStack() {
this.s = (E[]) new Object[100];
}
public int size(){
return t;
}
public boolean isEmpty(){
switch(size()){
case 0:
return true;
}
return false;
}
public E top() {
if(isEmpty())
throw new EmptyStackException();
return s[t-1];
}
public void push(E element) {
if(isEmpty())
s[0]= element;
else
s[t]= element;
t++;
}
public E pop() {
E x;
if(isEmpty())
throw new EmptyStackException();
else{
x = s[t-1];
s[t-1] = null;
t--;
}
return x;
}
}
jede Hilfe ??
Vielen Dank im Voraus
Der Algorithmus sieht richtig, können Sie die Implementierung von 'MyStack' zeigen? –
@HunterMcMillen Ich habe es zum Beitrag hinzugefügt –
Das ist eine LIFO-Datenstruktur richtig? Wie wäre es mit 'Deque st = new ArrayDeque ();' (Java 6+ erforderlich). –