题目:有一个n个正整数的数组a[0, n-1]作为输入,同时生成一个大小与a相同的数组array,然后处理a中的每个元素,如果当前的a[i]是奇数则直接添加到array中的最后一个元素后面,如果是偶数则从array中最后一个元素开始,向前依次删除所有奇数。我写了下面个程序,不知道为什么无法实现,希望大牛帮忙看下,为什么我这样调用无法实现功能...谢谢
package algorithm;public class TestAlgorithm {
int n = 7;
public static void main(String[] args) {
TestAlgorithm test = new TestAlgorithm();
int demo[] = {2, 3, 6, 4, 1, 7, 8};
test.function(demo);
for(int i = 0; i < demo.length; i++){
System.out.print(demo[i] + "\t");
}
}
public void function(int[] a){
int[] store = new int[n];
int j = 0;
for(int i = 0; i < a.length; i++){
if(a[i] % 2 == 0) //a[i]是偶数
 while(j > 0 && store[j - 1] % 2 != 0)
 store[j--] = 0; //删除前面的奇数
store[j++] = a[i];
}
return;
}
}

解决方案 »

  1.   

    因为你的function内部改变的demo的值不能反应到外部(跟C/C++可以修改引用传递参数即指针不同)。
    不妨将function的void 改为 int[],然后return store。
    调用的地方改为 int[] result = test.function(demo);下面去print result数组。
    算法没细看。
      

  2.   

    public class TestAlgorithm {
    int n = 7; public static void main(String[] args) {
    TestAlgorithm test = new TestAlgorithm ();
    int demo[] = { 2, 3, 6, 4, 1, 7, 8 };
    int[] r = test.function(demo);
    for (int i = 0; i < r.length; i++) {
    System.out.print(r[i] + "\t");
    }
    } public int[] function(int[] a) {
    int[] store = new int[n];
    int j = 0;
    for (int i = 0; i < a.length; i++) {
    if (a[i] % 2 == 0) // a[i]是偶数
    while (j > 0 && store[j - 1] % 2 != 0)
    store[j--] = 0; // 删除前面的奇数
    store[j++] = a[i];
    }
    return store;
    }
    }我让你改成这样,再看。
      

  3.   


    如果用static修饰,就可以,前提是参数不用传,用整个类的静态变量。