2014-12-07 139 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總是有大量的集合,比原始數組做得更好。 – 2014-12-07 20:33:51

+0

@MattCoubrough:true,數組是最不實用的數據結構,在中間的某處插入元素不再與堆棧有任何關係。當然,我寫的東西缺乏教育價值。我只是想在這種情況下給出一個關於如何處理數組的簡單例子。現在它由OP來優化程序並切換到列表或者更適合於那種問題。但是在跳轉到列表之前從數組開始並不完全理解後臺發生的事情仍然很好。 – GameDroids 2014-12-07 20:48:23

+0

也許你可以改進答案,也展示如何正確地做到這一點,或爲什麼陣列不適合這項工作? – 2014-12-07 20:55:30