顺序表基本操作(Java)

package com.zzw;

public interface IList {
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();

}


package com.zzw;


public  class SqList implements IList{
public Object[] listElem;
private int curLen;

public SqList(int maxSize){
curLen=0;
listElem=new Object[maxSize];
}
public void clear(){
curLen=0;
}
public int length(){
return curLen;
}
public boolean isEmpty(){
return curLen==0;
}
public Object get(int i){
if(i<0 || i>curLen-1)
try {
throw new Exception("第"+i+"个元素不存在");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listElem[i];
}
public void insert(int i,Object x){
if(curLen==listElem.length)
try {
throw new Exception("顺序表已满");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(i<0 || i>curLen)
try {
throw new Exception("插入位置不合法");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int j=curLen;j>i;j--)
listElem[j]=listElem[j-1];
listElem[i]=x;
curLen++;
}
public void remove(int i){
if(i<0 || i>curLen)
try {
throw new Exception("删除位置不合法");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int j=0;j<curLen;j++)
listElem[j]=listElem[j+1];
}
public int indexOf(Object x){
int j=0;
while(j<curLen && !listElem[j].equals(x))
j++;
if(j<curLen)
return j;
else
return -1;
}

public void display(){
for(int j=0;j<curLen;j++)
System.out.println(listElem[j]+"");
System.out.println();
}
}


package com.zzw;


public class SqListDAO {
public static void main(String[] args)throws Exception{
SqList L=new SqList(10);
L.insert(0, 'a');
L.insert(1, 'z');
L.insert(2, 'd');
L.insert(3, 'm');
L.insert(4, 'z');
L.insert(5, 'h');
L.insert(6, 'b');
int order =L.indexOf('c');
/*int c=L.length();
System.out.println(c);*/
if(order!=-1)
System.out.println("顺序表中第一次出现值为'z'的数据元素的位置为:"+order);
else
System.out.println("次顺序表中不包含值为'z'的数据元素!");
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值