From cf07ae774782d43b6b82d5716992533acbac793c Mon Sep 17 00:00:00 2001 From: quanxing Date: Sun, 14 Oct 2018 22:46:23 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E6=8F=92=E5=85=A5?= =?UTF-8?q?=E5=85=83=E7=B4=A0=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- java/05_array/Array.java | 76 ++++++++++++++++++++++------------------ 1 file changed, 41 insertions(+), 35 deletions(-) diff --git a/java/05_array/Array.java b/java/05_array/Array.java index 8ec2fe1d..fe751538 100644 --- a/java/05_array/Array.java +++ b/java/05_array/Array.java @@ -5,6 +5,7 @@ * 2)数组中的数据是int类型的; * * Author: Zheng + * modify: xing */ public class Array { //定义整型数据data保存数据 @@ -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; @@ -45,41 +75,6 @@ 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] + " "); @@ -87,6 +82,17 @@ public void printAll() { 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(); + } }