顺序表中要考虑到表空、表满、位置的合法性(是否在表真实长度内,与位置相关都需要。每次插入元素的时候,插入的位置之前要有数据,不能跳着放)。以下是表的实际长度usedsize和容量capacity。定义的时候要定义int[] elem;int型usedsize和静态int型变量capacity。
- 打印顺序表
思路:要考虑空表的情况。
代码:
public void display(){
for(int i=0;i<=usedSize;i++){
System.out.print(this.elem[i]+" ");
}
}
public boolean isEmpty(){
return this.usedSize==0;
}
- 在 pos 位置新增元素
思路:要考虑两点,一点是满的情况,要进行增容;一种是 pos的合法情况。若要在此位置上新增值,需要将此位置及以后的值向后移。
代码:
public void add(int pos,int data) {
if (pos < 0 || pos > this.usedSize) {
/* throw new RuntimeException("pos不合法");*/
System.out.println("不合法");
return;//要写一个return,因为下面还有别的函数,否则走到这里就不走了
}
if (isFull()) {
this.elem = Arrays.copyOf(this.elem, 2 * capacity);
capacity *= 2;
}
for(int i=this.usedSize;i>=pos;i--){
this.elem[i+1]=this.elem[i];
}
this.elem[pos]=data;
this.usedSize++;//长度加一
}
public boolean isFull(){
return this.usedSize == this.elem.length;
}
- 判定是否包含某个元素(值)
思路:考虑是否为空表。
代码:
public boolean contains(int toFind){
if((isEmpty())){
return false;
}
for(int i=0;i<=usedSize;i++){
if(this.elem[i]==toFind){
return true;
}
}
return false;
}
- 查找某个元素对应的位置(根据值查下标)
思路:考虑是否为空表。
代码:
public int search(int toFind){
if((isEmpty())){
return -1;
}
for(int i=0;i<=usedSize;i++){
if(this.elem[i]==toFind){
return i;
}
}
return -1;
}
- 获取 pos 位置的元素(根据下标查值)
思路:考虑两点,是否为空表,位置的合法性。
代码:
public int getPos(int pos){
if((isEmpty())){
// return -1;如果刚好元素为-1,则判断不出是元素还是空表
throw new RuntimeException("顺序表是空的");//手动抛出错误(异常)
}
if (pos < 0 || pos >= this.usedSize) {
throw new RuntimeException("pos不合法");
}
return this.elem[pos];
}
- 给 pos 位置的元素设为 value
思路:考虑两点,位置的合法性和是否为空表。
代码:
public void setPos(int pos, int value) {
if(pos<0||pos>usedSize){
throw new RuntimeException("pos不合法");
}
if(isEmpty()){
throw new RuntimeException("顺序表为空");
}
this.elem[pos]=value;
}
- 删除第一次出现的关键字key
思路:考虑里是否为空表。若要删除此位置上的值需要把后一个值往前移,将此位置上的值覆盖。
代码:
public void remove(int toRemove) {
if(isEmpty()){
throw new RuntimeException("顺序表为空");
}
int index=search(toRemove);
if(index==-1){
System.out.println("没有要删除的字");
}
for(int i=index;i<usedSize-1;i++){
this.elem[i]=this.elem[i+1];
}
this.usedSize--;
}
- 获取顺序表长度
代码:
public int size() {
return this.usedSize;
}
- 清空顺序表
思路:for循环
代码:
public void clear() {
for(int i=0;i<this.usedSize;i++){
this.elem[i]=0;
}
this.usedSize=0;
}