java实现顺序结构线性列表的函数代码
废话不多说,直接上代码
package com.ncu.list;
/**
*
* 顺序结构线性列表
*
*
*/
public class squencelist<t> {
private int size; // 线性表的长度
private object[] listarray;
private int currensize = 0; // 当前线性表中的数据
public squencelist() {
}
public squencelist(int size) {
this.size = size;
listarray = new object[size];
}
public void arraycopy(int index) {
object newarray[] = new object[size];
for (int i = 0; i < currensize; i++) {
if (i >= index) {
newarray[i] = listarray[i + 1];
} else {
newarray[i] = listarray[i];
}
}
listarray = newarray;
newarray = null; // 释放资源
}
/**
* 根据索引位置移除元素
*
* @param index
*/
public void remove(int index) {
index = index - 1;
if (index < 0 || index > currensize) {
system.out.println("线性表索引越界");
}
if (currensize == 0) {
system.out.println("线性表为空");
} else {
currensize--;
arraycopy(index);
if (currensize == 0) {
listarray = null;
}
}
}
/**
* 根据元素内容移除元素
*
* @param element
*/
public void removelocate(t element) {
for (int i = 0; i < currensize;) {
if (element.equals(listarray[i])) {
remove(i + 1);
} else {
i++;
}
}
}
/**
* 从线性表尾段插入数据
*
* @param element
*/
public void add(t element) {
if (currensize > size || currensize < 0) {
system.out.println("线性表索引越界");
} else {
listarray[currensize] = element;
currensize++;
}
}
private void insert(t element, int index) {
index = index - 1;
if (currensize > size || currensize < 0 || index < 0
|| index >= currensize) {
system.out.println("线性表索引越界");
} else {
object newarray[] = new object[size];
for (int i = 0; i < currensize; i++) {
if (i >= index) {
newarray[index] = element;
newarray[i + 1] = listarray[i];
} else {
newarray[i] = listarray[i];
}
}
listarray = newarray;
newarray = null;
currensize++;
}
}
/**
* 在指定索引位置插入数据
*
* @param element
* @param index
*/
public void add(t element, int index) {
if (index == size) {
add(element);
} else {
insert(element, index);
}
}
/**
* 删除线性表最后一个元素
*/
public void delete() {
if (isempty()) {
system.out.println("线性表为空,不能删除");
} else {
listarray[currensize - 1] = null;
currensize--;
}
}
/**
* 判读线性表是否为空
*
* @return
*/
public boolean isempty() {
if (currensize == 0) {
return true;
} else {
return false;
}
}
/**
* 根据索引找到相应的元素
*
* @param index
* @return
*/
public t get(int index) {
t obj = null;
if (isempty() || index > currensize || index < 0) {
system.out.println("线性表为空,不能删除");
} else {
obj = (t) listarray[index - 1];
}
return obj;
}
/**
* 清空线性表
*/
public void clear() {
size = 0;
currensize = 0;
}
/**
* 得到线性表当前的元素的个数
*
* @return
*/
public int size() {
return currensize;
}
public void showlist() {
if (currensize > 0) {
for (int i = 0; i < currensize; i++) {
system.out.println(listarray[i]);
}
} else {
system.out.println("线性表为空");
}
system.out.println("------------");
}
public static void main(string[] args) {
squencelist<integer> list = new squencelist<integer>(10);
}
}