python顺序表基本操作_Java-实现顺序表的基本操作

List.java

package com.wanali.java_ds.sqlist;

public interface List {

public boolean empty();

public void clear();

public int length();

public Object get(int i);

public void insert(int i, Object x) throws Exception;

public Object delete(int i);

public void display();

SqList.java

package com.wanali.java_ds.sqlist;

public class SqList implements List {

private Object[] elem;

private int curlength;

public SqList(int maxsize) {

curlength = 1;

elem = new Object[maxsize];

}

public boolean empty() {

return curlength == 0;

}

public int length() {

// TODO Auto-generated method stub

return curlength;

}

public void clear() {

curlength = 0;

System.out.println("表已经清空了!!!");

}

public Object get1(int i) {

return elem[i - 1];

}

public void insert(int i, Object x) throws Exception {

if (i < 0 || i > curlength)

throw new Exception("输入的参数不合法");

int maxsize = 10;

if (curlength == elem.length)

elem[maxsize] = elem[2 * maxsize];

for (int j = curlength; j > i; j--)

elem[j] = elem[j - 1];

elem[i] = x;

++curlength;

}

public Object delete(int i) {

for (int j = i; j < curlength; j++)

elem[j] = elem[j + 1];

--curlength;

return elem[i];

}

public void display() {

// TODO Auto-generated method stub

for (int i = 1; i < curlength; i++)

System.out.println(elem[i]);

}

public Object get(int i) {

// TODO Auto-generated method stub

System.out.println(elem[i]);

return null;

}

}

TestSqList.java

package com.wanali.java_ds.sqlist;

public class TestSqList {

public static void main(String[] args) {

SqList sqList = new SqList(10);

try {

sqList.insert(1, 10);

sqList.insert(2, 20);

sqList.insert(3, 30);

sqList.insert(4, 40);

System.out.println("按顺序输出表中的元素:");

sqList.display();

System.out.println("删除一个元素:");

sqList.delete(2);

sqList.display();

System.out.println("获得第i个元素:");

sqList.get(2);

System.out.println("清空顺序表:");

sqList.clear();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值