java的实现相对C语言,只是分配内存的方式不同。C语言用malloc,而java用new。
这里只是使用int数组做一个简单的实现,并没有太严谨。
废话不多说,直接上代码:
/**
* 线性表的顺序实现
*
* @author mkii
*/
public class SeqList {
// 默认数组容量
private final int DEFAULT_SIZE = 2;
// 扩容大小
private final int FACTORY = 2;
private int length;
private int size;
private int[] elems;
SeqList() {
initSeqList();
}
public int size(){
return size;
}
public int length(){
return length;
}
/**
* 初始化顺序表
*
*/
private void initSeqList(){
length = 0;
size = DEFAULT_SIZE;
elems = new int[DEFAULT_SIZE];
}
/**
* 判断顺序表是否为空
* @return
*/
private boolean emptySeqList(){
return (elems == null || length == 0 || size == 0);
}
/**
* 扩容,容量增加FACTORY
*
* @param a 原数组
*/
private void expansion(int[] a){
int[] newElems = new int[size + FACTORY];
int i;
for(i = 0; i < length; i++){
newElems[i] = a[i];
}
elems = newElems;
size += FACTORY;
}
/**
* 向顺序表中添加元素
*
* @param val 添加的元素
*/
public void addElem(int val){
if (length >= size){
System.out.println("容量不足,扩容!");
expansion(elems);
}
elems[length] = val;
length++;
System.out.println("添加元素成功");
}
/**
* 从顺序表中删除元素
*
* @param val 删除的元素值
*/
public void deleteElem(int val){
int i = 0;
int index = -1;
if (emptySeqList()){
System.out.println("空顺序表!");
return ;
}
for (i = 0; i < length; i++){
if(elems[i] == val){
index = i;
elems[i] = 0;
}
}
if (index == -1){
System.out.println("未找到元素!");
}
for (i = index; i < length-1; i++){
elems[i] = elems[i+1];
}
length--;
System.out.println("删除元素成功");
}
/**
* 修改顺序表中指定位置的元素
*
* @param index 位置索引
* @param val 更新为这个值
*/
public void updateSeqList(int index, int val){
if(index >= size || index >= length || index < 0){
System.out.println("索引错误!");
return ;
}
elems[index] = val;
System.out.println("更新元素成功");
}
/**
* 根据索引获取该处的元素
*
* @param index 元素
* @return int
* @throws Exception 越界
*/
public int readElem(int index) throws Exception{
if(index >= size || index >= length || index < 0){
System.out.println("索引错误!");
throw new Exception("索引越界!");
}
System.out.println("查找元素成功");
return elems[index];
}
/**
* 获取字符串形式的顺序表全部元素
*
* @return String
*/
public String readSeqList(){
StringBuilder stringBuilder = new StringBuilder();
String to = ":";
String spiltChar = ", ";
for(int i = 0; i < length; i++){
stringBuilder.append(i);
stringBuilder.append(to);
stringBuilder.append(elems[i]);
stringBuilder.append(spiltChar);
}
return stringBuilder.toString();
}
/**
* 销毁顺序表
*
*/
public void destroySeqList(){
if (!emptySeqList()){
elems = null;
length = 0;
size = 0;
}
}
/**
* 测试
*
*/
public static void main(String[] args) throws Exception{
SeqList seqList = new SeqList();
System.out.println(seqList.emptySeqList());
seqList.addElem(11);
seqList.addElem(22);
seqList.addElem(33);
System.out.println(seqList.readSeqList());
seqList.updateSeqList(0, 44);
System.out.println(seqList.readSeqList());
seqList.deleteElem(33);
System.out.println(seqList.readSeqList());
System.out.println(seqList.readElem(1));
}
}
纯属个人理解手撸,若有错误请指正,感谢!
源代码可以去我的码云拿https://gitee.com/mkii/studyTree