1.定义一个接口 IList .java
package zcf;
/**
* 增删改查 输出 遍历
* @author zcf
*
*/
public interface IList {
public void insert(int position,Object obj) throws Exception;
public void remove(int position) throws Exception;
public Object get(int positon) throws Exception;
public boolean isEmpty();
public void display();//输出所有元素
public int lentgth();
public void clear();
public int indexOf(Object obj);//首次出现该元素的序号
}
2.线性表具体实现 SqList .java
package zcf;
/**
* 数据结构 从新学习 之
*
* 线性表
* @author zcf
*
*/
public class SqList implements IList{
private Object[] listElem;//存储空间
private int curLen;//当前长度
public SqList(int maxSize) {
this.listElem = new Object[maxSize];
this.curLen = 0;
}
@Override
public void insert(int position, Object obj) throws Exception {
if (position <0 || position >curLen) {
throw new Exception("插入的数值不合法");
}
if (curLen == listElem.length) {
throw new Exception("存储空间已满");
}
for (int j = curLen; j >position; j--) {
listElem[j]=listElem[j-1];
}
listElem[position] = obj;
curLen++;
}
@Override
public void remove(int position) throws Exception{
if (position <0 || position >curLen-1) {
throw new Exception("删除的数值不合法");
}
for (int j = position; j < curLen; j++) {
listElem[j]=listElem[j+1];
}
curLen--;
}
@Override
public Object get(int positon) throws Exception{
if (positon<0||positon>curLen-1) {
throw new Exception("");
}
return listElem[positon];
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return curLen == 0;
}
@Override
public void display() {
System.out.print("[");
for(int i=0;i<curLen;i++){
if (i !=curLen-1) {
System.out.print(listElem[i]+",");
}else {
System.out.print(listElem[i]);
}
}
System.out.print("]");
}
@Override
public int lentgth() {
// TODO Auto-generated method stub
return curLen;
}
@Override
public void clear() {
curLen = 0;
}
@Override
public int indexOf(Object obj) {
int i = 0;
while ( i < curLen&&!listElem[i].equals(obj) ) {
i++;
}
if (i<curLen) {
return i;
}
return -1;
}
}
3.测试
1.查找线性表中第i个元素的前驱
package zcf;
import java.util.Scanner;
public class ListTest {
public static void main(String[] args) throws Exception {
SqList L = new SqList(100);
int len = 30;
for (int i = 0; i < len; i++) {
L.insert(i, i);
}
L.display();
int i = new Scanner(System.in).nextInt();
if (0<i&&i<=len) {
System.out.println("前驱是 : "+L.get(i-1));
}else {
System.out.println("没有前驱");
}
}
}