2014-12-07 3 views
-2

Я создаю метод в вызове вызова стека в этом методе. Я хочу добавить элемент после того, как элемент является конкретной формой, например, если число в стеке равно «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; 
     } 
    } 
} 

ответ

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 
     }    
    } 

И это все. выглядит сложным и является далеко не лучшим или самым эффективным решением. Но это работает, и я надеюсь, что это поможет вам продвинуться дальше!

+0

Это может быть только я, но я не уверен, что писать код с использованием неправильных структур данных для работы делает хороший дидактический пример. В Java всегда было много коллекций, которые могли бы работать лучше, чем исходные массивы для этой проблемы. –

+0

@MattCoubrough: true, массивы - это наименее практичная структура данных здесь, а вставки элементов где-то посередине больше не имеют отношения к стекам. И то, что я написал, не имеет образовательной ценности, наверняка. Я просто пытался дать «простой» пример того, как обрабатывать массивы в этом случае. Теперь это до OP, чтобы оптимизировать программу и переключиться на Списки или что когда-либо лучше подходит для такого рода проблем. Но по-прежнему полезно начинать с массивов, прежде чем переходить к спискам, не понимая, что происходит в фоновом режиме. – GameDroids

+0

Возможно, вы могли бы улучшить ответ, чтобы показать, как это сделать правильно или почему массивы не подходят для работы? –

Смежные вопросы