顺序表
使用顺序结构实现的线性表称为顺序表。
以下为代码实现内容:
1.创建一个List接口
package com.songdan.list;
//线性表接口类
public interface List {
//获得线性表长度
public int ListLength();
//判断线性表是否为空
public boolean ListEmpty();
//插入元素
public void ListInsert(int index,Object obj) throws Exception;
//删除元素
public Object ListDelete(int index) throws Exception;
//获取指定位置的元素
public Object GetElement(int index) throws Exception;
}
2.设计一个顺序表
List.java
package com.songdan.list;
//线性表接口类
public interface List {
//获得线性表长度
public int ListLength();
//判断线性表是否为空
public boolean ListEmpty();
//插入元素
public void ListInsert(int index,Object obj) throws Exception;
//删除元素
public Object ListDelete(int index) throws Exception;
//获取指定位置的元素
public Object GetElement(int index) throws Exception;
}
3.创建SequenceList.java实现代码
package com.songdan.sequencelist;
import com.songdan.list.List;
public class SequenceList implements List{
//线性表的默认长度
private final int DefaultSize = 10;
//最大长度
private int MaxSize;
//当前长度
private int size;
Object []listArray;
public SequenceList(){
init(DefaultSize);
}
public SequenceList(int num){
init(num);
}
//初始化方法
public void init(int size) {
this.MaxSize = size;
this.size = 0;
listArray = new Object[size];
}
public Object GetElement(int index) throws Exception{
if(index < 0 || index >= size)
throw new Exception("参数错误");
else return listArray[index];
}
@Override
public Object ListDelete(int index) throws Exception{
//空链表
if (size == 0) {
throw new Exception("空链表");
}
//下标不正确
else if(index < 0 || index >= size){
throw new Exception("参数不正确");
}
//链表移动
else {
Object obj = listArray[index];
for(int i = index;i+1 < size;i++){
listArray[i] = listArray[i+1];
}
size--;//大小要减1
return obj;
}
}
@Override
public void ListInsert(int index, Object obj) throws Exception {
//当前线性表已满,不能插入
if(size == MaxSize)
throw new Exception("线性表已满,无法插入");
//插入位置是否合法
else if(index < 0 || index > size){
throw new Exception("参数不正确");
}
else {
for (int i = index; i < size; i++) {
listArray[i+1] = listArray[i];
}
listArray[index] = obj;
}
size++;
}
@Override
public int ListLength() {
return size;
}
@Override
public boolean ListEmpty() {
return size == 0;
}
//遍历表
public void TraveList(){
int i = 0;
for (Object obj : listArray) {
System.out.println("第" + i++ + "个元素是" + obj );
if(i==size)
break;
}
}
}
4.创建一个测试类,用来实现并观察代码是否能正确运行出想要的结果
package com.songdan.sequencelist;
import com.songdan.student.Student;
public class TestSL {
public static void main(String[] args) throws Exception {
SequenceList sequenceList = new SequenceList(10);
sequenceList.ListInsert(0, 100);
sequenceList.ListInsert(1, "hahh1");
sequenceList.ListInsert(2, 600);
sequenceList.ListInsert(3, "年后");
sequenceList.TraveList();
}
}