数据结构——顺序表结构
public interface IList {
public void clear ();
public boolean isEmpty ();
public int length ();
public Object get (int i) throws Exception;
public void insert (int i,Object x) throws Exception;
public void remove (int i) throws Exception;
public int indexOf (Object x);
public void display ();
}
public class SqList implements IList {
private Object[] ListElem;
private int curLen;
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) throws Exception {
if (0 <i||i>curLen-1 )
throw new Exception("第" +i+"个元素不存在" );
return ListElem[i];
}
@Override
public void insert (int i, Object x)throws Exception {
if (curLen == ListElem.length)
throw new Exception("顺序表已满" );
if (i<0 ||i>curLen)
throw new Exception("插入的位置不合理" );
for (int j = curLen;j>i;j--)
ListElem[j] = ListElem[j-1 ];
ListElem[i] = x;
curLen++;
}
@Override
public void remove (int i) throws Exception{
if (i<0 ||i>curLen)
throw new Exception("删除的位置不合理" );
for (int j = i; j<curLen-1 ;j++)
ListElem[j] = ListElem[j+1 ];
curLen++;
}
@Override
public int indexOf (Object x) {
int j = 0 ;
while (j<curLen&&!ListElem[j].equals(x))
j++;
if (j<curLen)
return j;
else
return -1 ;
}
@Override
public void display () {
for (int j = 0 ;j<curLen;j++)
System.out.print(ListElem[j]+" " );
System.out.println(" " );
}
}
public class Example2_1 {
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' );
int order = L.indexOf('z' );
if (order != -1 )
System.out.println("顺序表中第一次出现的值为'z'的数据的位置是:" +order);
else
System.out.println("顺序表中不包含值为'z'的数据元素" );
}
}