定义一个List接口:
package com.edu.dataStructure.list;
interface List {
//获取线性表的长度
public int getLength() ;
//判断顺序表是不是为空
public boolean isEmpty();
//为顺序表添加元素
public void insert(int index,Object x) throws Exception;
//为顺序表删除元素
public Object delete(int index) throws Exception;
//获取指定位置上的元素
public Object get(int index)throws Exception;
//查找顺序表中元素的位置
public int search(Object x)throws Exception;
//遍历元素
public void input();
}
定义一个Sq类实现List中的方法:
package com.edu.dataStructure.list;
public class Sq implements List {
private final int defaultsize = 10;
private int size;
private int max;
Object listElem[];
Sq() {
init(defaultsize);
}
Sq(int num) {
init(num);
}
public void init(int size) {
this.max = size;
this.size = 0;
listElem = new Object[size];
}
@Override
public int getLength() {
return size;
}
@Override
public boolean isEmpty() {
if (size > 0) {
return false;
} else {
return true;
}
//或者可以这样写return size==0
}
@Override
public void insert(int index, Object x) throws Exception {
if (size == max) {
throw new Exception("顺序表已满");
} else if (index < 0 && index > max) {
throw new Exception("参数错误");
} else {
for (int i = index; i < size; i++) {
listElem[i + 1] = listElem[i];
}
listElem[index] = x;
size++;
}
}
@Override
public Object delete(int index) throws Exception {
if (size == 0) {
throw new Exception("该顺序表为空");
} else if (index < 0 || index >= size) {
throw new Exception("参数错误");
} else {
Object x = listElem[index];
for (int i = index; i < size - 1; i++) {
listElem[i] = listElem[i + 1];
}
size--;
return x;
}
}
@Override
public Object get(int index) throws Exception {
if (index > size || index < 0) {
throw new Exception("参数错误");
} else {
return listElem[index];
}
}
@Override
public int search(Object x) throws Exception {
for (int i = 0; i < size; i++) {
if (x.equals(listElem[i])) {
return i;
}
}
return -1;
}
@Override
public void input() {
for(Object list:listElem){
System.out.print(list+" ");
}
}
}
测试类:
package com.edu.dataStructure.list;
public class Test {
public static void main(String[] args) throws Exception {
Sq s=new Sq(10);
s.insert(0,5);
s.insert(1,6);
s.insert(2,5);
s.insert(3,9);
s.insert(4,7);
System.out.println("顺序表遍历");
s.input();
s.delete(3);
System.out.println();
System.out.println("删除后的顺序表");
s.input();
}
}
运行结果:
顺序表遍历
5 6 5 9 7 null null null null null
删除后的顺序表
5 6 5 7 7 null null null null null