JAVA实现顺序表的增删查改
package Ilist;
public class List{
int N=10,count=0;
int []array=new int[N];
// 增
//position为要插入的位置 item为要插入的数据
public boolean insert(int position,int item) {
boolean insert = false;
if(!full()){
//如果在原有数组没查找到item以保证不插入相同的数据
if(!search(item)) {
for(int i=count;i>position;i--) {
array[i]=array[i-1];
}
array[position]=item;
count++;
insert=true;
}
else {
System.out.println("The data already exists!");
}
}
else {
System.out.println("The array is full!");
}
return insert;
}
// 删
public boolean remove(int position) {
boolean remove=false;
int item=0;
if(!empty()) {
if(search(item)) {
if(position<=count&&position>=0)
{
for(int i=position;i<=count-1;i++) {
array[i]=array[i+1];
}
array[count]=0;
count--;
remove=true;
}
else {
System.out.println("Not in scape!");
}
}
else {
System.out.println("The data does not exsit!");
}
}
else {
System.out.println("The array is empty!");
}
return remove;
}
// 查
public int indexof(int x) {
int j=0;
while(j<=count&&array[j]!=x) {
j++;
}
if(j<=count) {
return j;
}
else {
return -1;
}
}
// 判断表是否为空
private boolean empty() {
return count<=0;
}
// 判断所修改的变量是否存在
private boolean search(int item) {
boolean search=false;
for(int i:array) {
if(i==item) {
search=true;
}
else {
}
}
return search;
}
// 判断表是否已满
private boolean full() {
return count>=N;
}
// 打印表
public void display() {
for(int i:array) {
System.out.println(i);
}
}
}
*****************************************
//测试类
package Ilist;
public class Test {
public static void main(String[] args) {
List list1 =new List();
list1.insert(0,1);
list1.insert(1,2);
list1.insert(2,3);
list1.insert(3,5);
//当下标为3、4时都插入5 array[4]插入失败
list1.insert(4,5);
list1.insert(5,6);
list1.insert(6,7);
list1.insert(7,8);
list1.insert(8,9);
list1.display();
System.out.println("**********");
list1.remove(4);
list1.display();
System.out.println("**********");
list1.remove(0);
list1.display();
System.out.println(list1.indexof(9));
}
}
运行结果:
The data already exists!
1
2
3
5
0
6
7
8
9
0
1
2
3
5
6
7
8
9
0
0
2
3
5
6
7
8
9
0
0
0
6