Skip to content

Commit

Permalink
修改了插入元素的方法
Browse files Browse the repository at this point in the history
  • Loading branch information
quanxing committed Oct 14, 2018
1 parent 80550d6 commit cf07ae7
Showing 1 changed file with 41 additions and 35 deletions.
76 changes: 41 additions & 35 deletions java/05_array/Array.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 2)数组中的数据是int类型的;
*
* Author: Zheng
* modify: xing
*/
public class Array {
//定义整型数据data保存数据
Expand All @@ -27,6 +28,35 @@ public int find(int index){
return data[index];
}

//插入元素:头部插入,尾部插入
public boolean insert(int index, int value){
//数组中无元素

//if (index == count && count == 0) {
// data[index] = value;
// ++count;
// return true;
//}

// 数组空间已满
if (count == n) {
System.out.println("没有可插入的位置");
return false;
}
// 如果count还没满,那么就可以插入数据到数组中
// 位置不合法
if (index < 0||index > count ) {
System.out.println("位置不合法");
return false;
}
// 位置合法
for( int i = count; i > index; --i){
data[i] = data[i - 1];
}
data[index] = value;
++count;
return true;
}
//根据索引,删除数组中元素
public boolean delete(int index){
if (index<0 || index >=count) return false;
Expand All @@ -45,48 +75,24 @@ public boolean delete(int index){
--count;
return true;
}

//向数组中插入一个元素
public boolean insert(int index, int value){
if (index<0 || index>=count) return false;
//当实际存储的个数等于数组的最大长度就不让新增
if (count == n) return false;
//数组长度增加1。不需要初始化
/*int[] arr = new int[count+1];
for (int i = 0; i < data.length; i++) {
arr[i] = data[i];
}
data=arr;*/

for (int i = count-1; i>=index; --i){
data[i+1] = data[i];
}
data[index] = value;
++count;
return true;
}

public boolean insertToTail(int value) {

//当实际存储的个数等于数组的最大长度就不让新增
if (count == n) return false;
//数组长度增加1
/*int[] arr = new int[count+1];
for (int i = 0; i < data.length; i++) {
arr[i] = data[i];
}
data=arr;*/
data[count++] = value;
return true;
}

public void printAll() {
for (int i = 0; i < count; ++i) {
System.out.print(data[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {
ArrayOperate array = new ArrayOperate(5);
array.printAll();
array.insert(0, 3);
array.insert(0, 4);
array.insert(1, 5);
array.insert(3, 9);
array.insert(3, 10);
//array.insert(3, 11);
array.printAll();
}


}

0 comments on commit cf07ae7

Please sign in to comment.