Grundsätzlich mein Code funktioniert gut, aber ich möchte es flexibler zu aktualisieren, so dass alle Ideen, wie ich den Header der Merge-Methode ändern kann, so dass es als Parameter erhalten (und zurück) Stapel, die Array-basiert sind oder Referenz-basiert? Ich werde etwas Code posten, wenn mehr nötig ist, werde ich es aktualisieren. Danke im Voraus.Ändern Sie die Kopfzeile der Zusammenführungs-Methode, so dass sie als Parameter (und Rückgabe) Stapel, die Array-basiert oder Referenz-basiert sind, empfangen kann?
/**
* merge: Given two stacks containing Integer objects in increasing order from the bottom up,
* create a third stack such that the Integer objects are in decreasing order from the bottom up.
* If an item appears n times in the two given stacks, it will appear n times in the new stack.
*
* @param s1 the first stack
* @param s2 the second stack
* @return the new stack, with the items from the two given stacks merged.
*/
public static StackReferenceBased merge(StackArrayBased s1, StackReferenceBased s2)
{
StackReferenceBased newStack = new StackReferenceBased();
Integer i1 = new Integer(-1);
Integer i2 = new Integer(-1);
if (!s1.isEmpty())
i1 = (Integer)s1.pop();
if (!s2.isEmpty())
i2 = (Integer)s2.pop();
while (!s1.isEmpty() && !s2.isEmpty()) {
System.out.println("Comparing " + i1 + " and " + i2);
if (i1.compareTo(i2) < 0) {
newStack.push(i2);
//Get next item from second stack
i2 = (Integer)s2.pop();
}
else {
newStack.push(i1);
//Get next item from first stack
i1 = (Integer)s1.pop();
}
}
// At this point, s1 and/or s2 are empty.
if (s1.isEmpty()) {
newStack.push(i2);
while (!s2.isEmpty()) {
newStack.push(s2.pop());
}
}
if (s2.isEmpty()) {
newStack.push(i1);
while (!s1.isEmpty()) {
newStack.push(s1.pop());
}
}
return newStack;
}
Dank! Das hat funktioniert, woah es ziemlich offensichtlich war. –