添加元素到堆栈

时间:2014-12-07 19:51:38

标签: java stack

我在此方法中添加堆栈调用中的方法我希望在元素特定表单使用后添加元素,例如,如果堆栈中的数字是“1 2 3 5”并且我选择数字3并输入数字4堆栈应该是“1 2 3 4 5”这是我的尝试

int a[] = new int[6];
int Top = -1;

public void push() {
    if (Top > 6) {
        System.out.println(" the Stack Ovelflow");
    } else {
        Top = Top + 1;
        String m = JOptionPane.showInputDialog("enter the element stack");
        a[Top] = Integer.parseInt(m);
    }
}

public void adding() {
    String s = JOptionPane.showInputDialog("enter the element u want to add after it");
    int x = Integer.parseInt(s);
    String s2 = JOptionPane.showInputDialog("enter the element u want to add to stack");
    int d = Integer.parseInt(s2);
    for (int i = 0; i < a.length; i++) {
        if (a[i] == x) {
            a[i + 1] = d;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要确保您的支持数组a有足够的空间,以便插入新元素。

int[] a= new int[]{1,2,3,5};  // this has only 4 elements, you can't add a 5th

所以你可以这样做:

public void adding(){
  // ask user for input.... and all that
  // you need an array with one more element than a. lets call it b

  int[] b = new int[a.length + 1];

  // now you need to search for x. (this is, if x is a number in your array and not an index..it wasn't clear to me)
  // so if x is a number in the array (and not the index) you need to get the index of that number:
  int index = 0;
  for (; index < a.length; index++) {  // your index variable will increment on each step
      if (a[index] == x) {
          break;            // and you break out of the loop once you found x
      }
  }

  // now you know the index of x
  // first make a copy of the partial array after x (in your example its just {5})
  int[] c = Arrays.copyOfRange(a, index, a.length);  // this will copy all elements of a from "index" to "length"

  // and here the loop that will actually insert the new number and move the rest:

   int cIndex=0;  // we need that counter later to loop through the new array c
    for (int i = 0; i < b.length; i++) { // loop through every element of b
        if (i <= index) {   // if i is currently smaller than your wanted index (there where you will find x)
            b[i] = a[i];  // then just copy the contents of a
        } else if (i == index+1) {  // we just stepped over x
            b[i] = d;         // so you can add your new number here
        } else {
            b[i] = c[cIndex];   // and here you copy the rest into b (the partial array we called c earlier)
            cIndex++;  // we need that new index, to get always the next element
        }            
    }

就是这样。看起来很复杂,到目前为止还不是最好或最有效的解决方案。但它有效,我希望它可以帮助你进一步发展!