2016-05-18 5 views
1

基本的には私のコードは正常に動作しますが、より柔軟になるように更新したいので、マージメソッドのヘッダーを変更して、配列ベースのスタックまたは参照ベース?私はいくつかのコードを投稿するつもりです、もっと必要な場合は、私はそれを更新します。前もって感謝します。マージメソッドのヘッダーを変更して、配列ベースまたは参照ベースのスタックをパラメータとして受け取ることができるようにします。

/** 
* 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; 
} 

答えて

0

更新受け入れ、共通のインタフェースを返すために署名、StackInterface

public static StackInterface merge(StackInterface s1, StackInterface s2) 
+0

ありがとう!これはうまくいった。 –

関連する問題