代码方面:
在昨天的基础上进行了根据给定索引进行插入删除的顺序表操作以及返回指定元素下标的操作。
package First;
public class SequentialList {
public static final int MAX_LENGTH=10;
int length;
int[] data;
public SequentialList()
{
length=0;
data = new int[MAX_LENGTH];
}
public SequentialList(int[] paraArray)
{
data = new int[MAX_LENGTH];
length = paraArray.length;
for(int i=0;i<paraArray.length;i++)
{
data[i] = paraArray[i];
}
}
public String toString()
{
String resultString="";
if(length==0)
{
return "empty";
}
for(int i=0;i<length-1;i++)
{
resultString += data[i]+", ";
}
resultString+=data[length-1];
return resultString;
}
public void reset()
{
length=0;
}
/*查找对饮元素并返回索引*/
public int indexOf(int paraValue){
int tempPosition=-1;
for(int i=0;i<length;i++){
if(data[i]==paraValue){
tempPosition=i;
break;
}
}
return tempPosition;
}
public boolean insert(int paraPosition,int paraValue){
/*栈满处理*/
if(length==MAX_LENGTH){
System.out.println("List full.");
return false;
}
/*下标越界处理*/
if((paraPosition<0)||(paraPosition>length)){
System.out.println("The position "+paraPosition+"is out of bounds.");
return false;
}
/*插入元素*/
for(int i=length;i>paraPosition;i--){
data[i]=data[i-1];
}
data[paraPosition]=paraValue;
length++;
return true;
}
public boolean delete(int paraPosition){
if((paraPosition<0)||(paraPosition>length)){
System.out.println("The position "+paraPosition+"is out of bound.");
return false;
}
/*从头到尾*/
for(int i=paraPosition;i<length-1;i++){
data[i]=data[i+1];
}
length--;
return true;
}
public static void main(String[] args)
{
int[] tempArray={1,4,6,9};
SequentialList tempFirstList=new SequentialList(tempArray);
System.out.println("Initialized, the list is: "+tempFirstList.toString());
System.out.println("Again, the list is: "+tempFirstList);
int tempValue = 4;
int tempPosition = tempFirstList.indexOf(tempValue);
System.out.println("The position of " + tempValue + " is " + tempPosition);
tempValue = 5;
tempPosition = tempFirstList.indexOf(tempValue);
System.out.println("The position of " + tempValue + " is " + tempPosition);
tempPosition = 2;
tempValue = 5;
tempFirstList.insert(tempPosition, tempValue);
System.out.println(
"After inserting " + tempValue + " to position " + tempPosition + ", the list is: " + tempFirstList);
tempPosition = 8;
tempValue = 10;
tempFirstList.insert(tempPosition, tempValue);
System.out.println(
"After inserting " + tempValue + " to position " + tempPosition + ", the list is: " + tempFirstList);
tempPosition = 3;
tempFirstList.delete(tempPosition);
System.out.println("After deleting data at position " + tempPosition + ", the list is: " + tempFirstList);
for (int i = 0; i < 8; i++) {
tempFirstList.insert(i, i);
System.out.println("After inserting " + i + " to position " + i + ", the list is: " + tempFirstList);
}
tempFirstList.reset();
System.out.println("After reset, the list is: " + tempFirstList);
}
}
单词方面: