数据结构之线性表java实现

package com.cb.java.algorithms.datastructure.yanweimindatastructure.list;


/**
 * 顺序表的特点 在线性表中逻辑上相邻的数据元素,在物理存储位置上也是相邻的。<br>
 * 存储密度高,但要预先分配,可能会造成空间的浪费。 <br>
 * 便于随机存取 不便于插入和删除操作,会引起大量的数据元素的移动
 * 
 * @author 36184
 *
 */
public class SeqList implements List {
final int defaultSize = 10;
int listLength = 10;// 线性表的容量
int curSize = 0; // 当前线性表中元素个数
Object[] list = null; // 线性表


/**
* 初始化线性表

* @param size
*            线性表长度
*/
private void init(int size) {
listLength = size;
curSize = 0;
list = new Object[listLength];
}


public SeqList() {
init(defaultSize);
}


public SeqList(int size) {
init(size);
}


@Override
public void insert(int i, Object object) throws Exception {
if (curSize == listLength)
throw new Exception("线性表已满");
if (i < 0 || i > listLength)
throw new Exception("插入位置有误");
for (int j = curSize; j > i; j--) {
list[j] = list[j - 1];
}
list[i] = object;
curSize++;
}


@Override
public Object delete(int i) throws Exception {
if (curSize == 0) {
throw new Exception("线性表为空");
}
if (i < 0 || i >= listLength) {
throw new Exception("删除位置有误");
}
Object deleteObj = list[i];
for (int j = i; j < curSize; j++) {
list[j] = list[j + 1];
}
curSize--;
return deleteObj;
}


@Override
public Object getElem(int i) throws Exception {
if (i < 0 || i > curSize - 1) {
throw new Exception("获取元素的位置参数有误");
}
return list[i];
}


/**
* 获取该元素的前一个元素

* @param thisElem
* @return
*/
public Object getPriorElem(Object thisElem) {
if (indexOf(thisElem) > 0) {
return list[indexOf(thisElem) - 1];
} else
return null;
}


public Object getNextElem(Object thisElem) {
if (indexOf(thisElem) < curSize - 1) {
return list[indexOf(thisElem) + 1];
} else
return null;
}


@Override
public int length() {
return curSize;
}


@Override
public boolean isEmpty() {
return curSize == 0;
}


@Override
public void clear() {
curSize = 0;
}


@Override
public void destroy() {
list = null;
}


@Override
public int indexOf(Object object) {
for (int i = 0; i < curSize; i++) {
if (list[i].equals(object))
return i;
}
return -1;
}


@Override
public void display() {
for (int i = 0; i < curSize; i++)
System.out.print(list[i] + "\t");
System.out.println();
}


}

猜你喜欢

转载自blog.csdn.net/u013230189/article/details/80653973