数据结构--链表的操作(顺序结构)

package list;

interface List{

public void clear();

public boolean isEmpty();

public int length();

public Object get(int i);

public void insert(int i,Object x);

public void remove(int i);

public int indexOf(Object x);

public void display();

}

 class SqList implements List{

public Object[] listElem;

//顺序表当前长度

private int curLen

//顺序表的最大容量

//public static final int MaxSize = 20;

//构造一个容量为MaxSize的空顺序表函数

public  SqList(int MaxSize) {

curLen =0;

listElem = new Object[MaxSize];

}

@Override

public void clear() {

curLen =0;

}


@Override

public boolean isEmpty() {

return curLen==0;

}


@Override

public int length() {

return curLen;

}

@Override

public Object get(int i) {

if (i<0||i>curLen-1) {

try {

throw new Exception("第"+i+"个元素不存在");

} catch (Exception e) {

e.printStackTrace();

}

}

return listElem[i];

}


@Override

public void insert(int i, Object x) {

if (i<0||i>=listElem.length) {

try {

throw new Exception("插入的位置不合法,请重新选择插入位置!");

} catch (Exception e) {

e.printStackTrace();

}

}else{

for(int k=curLen;k>i;k--){

listElem[k]=listElem[k-1];

}

listElem[i]=x;

curLen++;

}

}

@Override

public void remove(int i) {

if (i<0||i>listElem.length-1) {

try {

throw new Exception("删除的位置不合法");

} catch (Exception e) {

e.printStackTrace();

}

}

else {

for(int k =i+1;k<listElem.length;k++){

listElem[k-1]=listElem[k];

}

}

curLen--;

}


@Override

public int indexOf(Object x) {

int i=0;

while(i<curLen&&!listElem[i].equals(x)){

i++;

}

if(i<curLen)

return i;

else

return -1;

}

public int directprior(int i){

int temp=0;

if (i<0||i>listElem.length) {

try {

throw new Exception("前驱不存在");

} catch (Exception e) {

e.printStackTrace();

}

}

else

temp=i-1;

return temp;

}

@Override

public void display() 

{

for(int i=0;i<curLen;i++)

System.out.print(listElem[i]+" ");

System.out.println("");

}

}

public class IList{

public static void main(String [] args){

SqList List=new SqList(10);

List.insert(0, 'a');

List.insert(1, 'b');

List.insert(2, 'c');

List.insert(3, 'd');

List.insert(4, 'e');

List.insert(5, 'f');

List.insert(6, 'g');

List.display();

System.out.println("第一次出现e的位置是:");

int order =List.indexOf('e');

System.out.println(order+1);

int key=List.directprior(3);

System.out.println("位置3前面的值是:"+List.listElem[key]);

}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值