55 * 2)数组中的数据是int类型的;
66 *
77 * Author: Zheng
8+ * modify: xing
89 */
910public class Array {
1011 //定义整型数据data保存数据
@@ -27,6 +28,35 @@ public int find(int index){
2728 return data [index ];
2829 }
2930
31+ //插入元素:头部插入,尾部插入
32+ public boolean insert (int index , int value ){
33+ //数组中无元素
34+
35+ //if (index == count && count == 0) {
36+ // data[index] = value;
37+ // ++count;
38+ // return true;
39+ //}
40+
41+ // 数组空间已满
42+ if (count == n ) {
43+ System .out .println ("没有可插入的位置" );
44+ return false ;
45+ }
46+ // 如果count还没满,那么就可以插入数据到数组中
47+ // 位置不合法
48+ if (index < 0 ||index > count ) {
49+ System .out .println ("位置不合法" );
50+ return false ;
51+ }
52+ // 位置合法
53+ for ( int i = count ; i > index ; --i ){
54+ data [i ] = data [i - 1 ];
55+ }
56+ data [index ] = value ;
57+ ++count ;
58+ return true ;
59+ }
3060 //根据索引,删除数组中元素
3161 public boolean delete (int index ){
3262 if (index <0 || index >=count ) return false ;
@@ -45,48 +75,24 @@ public boolean delete(int index){
4575 --count ;
4676 return true ;
4777 }
48-
49- //向数组中插入一个元素
50- public boolean insert (int index , int value ){
51- if (index <0 || index >=count ) return false ;
52- //当实际存储的个数等于数组的最大长度就不让新增
53- if (count == n ) return false ;
54- //数组长度增加1。不需要初始化
55- /*int[] arr = new int[count+1];
56- for (int i = 0; i < data.length; i++) {
57- arr[i] = data[i];
58- }
59- data=arr;*/
60-
61- for (int i = count -1 ; i >=index ; --i ){
62- data [i +1 ] = data [i ];
63- }
64- data [index ] = value ;
65- ++count ;
66- return true ;
67- }
68-
69- public boolean insertToTail (int value ) {
70-
71- //当实际存储的个数等于数组的最大长度就不让新增
72- if (count == n ) return false ;
73- //数组长度增加1
74- /*int[] arr = new int[count+1];
75- for (int i = 0; i < data.length; i++) {
76- arr[i] = data[i];
77- }
78- data=arr;*/
79- data [count ++] = value ;
80- return true ;
81- }
82-
8378 public void printAll () {
8479 for (int i = 0 ; i < count ; ++i ) {
8580 System .out .print (data [i ] + " " );
8681 }
8782 System .out .println ();
8883 }
8984
85+ public static void main (String [] args ) {
86+ ArrayOperate array = new ArrayOperate (5 );
87+ array .printAll ();
88+ array .insert (0 , 3 );
89+ array .insert (0 , 4 );
90+ array .insert (1 , 5 );
91+ array .insert (3 , 9 );
92+ array .insert (3 , 10 );
93+ //array.insert(3, 11);
94+ array .printAll ();
95+ }
9096
9197
9298}
0 commit comments