Java 向堆栈添加元素
我在stack call中创建了一个方法adding在这个方法中我想在元素是特定形式后添加元素使用例如,如果堆栈中的数字是1 2 3 5,我选择数字3并输入数字4,堆栈应该是1 2 3 4 5这是我的尝试Java 向堆栈添加元素,java,stack,Java,Stack,我在stack call中创建了一个方法adding在这个方法中我想在元素是特定形式后添加元素使用例如,如果堆栈中的数字是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 {
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;
}
}
}
您需要确保备份数组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
}
}
就这样。看起来很复杂,但这并不是最好或最有效的解决方案。但它是有效的,我希望它能帮助你走得更远 可能只有我一个人,但我不认为使用错误的数据结构编写代码是一个很好的教学例子。java总是有很多的集合,它比原始数组的工作更能解决这个问题。@ MattouBrou:没错,数组是最不实用的数据结构,插入中间的某个元素已经不再与栈有关。当然,我写的东西缺乏教育价值。我只是想给出一个简单的例子,说明在这种情况下如何处理数组。现在轮到OP来优化程序并切换到列表或更适合这种问题的东西。但是,在跳到列表之前先从数组开始,而不完全了解背景中发生了什么,这仍然是一件好事。也许您可以改进答案,以说明如何正确地执行此操作,或者为什么数组不适合此工作?