编写一个程序 ,实现顺序表的基本操作,添加,删除等等。
具体实现以下操作:
// 打印顺序表
public void toString() { }
// 新增元素,默认在数组最后新增
public void add(int data) { }
// 在 pos 位置新增元素
public void add(int pos, int data) { }
// 判定是否包含某个元素
public boolean contains(int toFind) { return true; }
// 查找某个元素对应的位置
public int indexOf(int toFind) { return -1; }
// 获取 pos 位置的元素
public int get(int pos) { return -1; }
// 给 pos 位置的元素设为 value
public void set(int pos, int value) { }
//删除第一次出现的关键字key
public void remove(int toRemove) { }
// 获取顺序表长度
public int size() { return 0; }
// 清空顺序表
public void clear() { }
具体实现代码:
import java.util.Arrays;
public class ArrayList {
public int[] elem;
public int usedSize;
public ArrayList(){
this.elem=new int[5];
}
// 打印顺序表
public void mytoString() {
for(int i=0;i<this.usedSize;i++){
System.out.println(this.elem[i]+"");
}
System.out.println();
}
// 新增元素,默认在数组最后新增
public void add(int data) {
if(isFull()){
this.elem= Arrays.copyOf(this.elem,2*this.elem.length);
}
this.elem[this.usedSize]=data;
this.usedSize++;
}
public boolean isFull(){
if(this.usedSize==this.elem.length){
return true;
}
return false;
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
if(pos < 0 || pos > this.usedSize) {
System.out.println("pos位置不合法!");
return;
}
if(isFull()){
this.elem= Arrays.copyOf(this.elem,2*this.elem.length);
}
for (int i = this.usedSize-1; i >= pos ; i--) {
this.elem[i+1] = this.elem[i];
}
this.elem[pos] = data;
this.usedSize++;
}
// 判定是否包含某个元素
public boolean contains(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if(this.elem[i] == toFind) {
return true;
}
}
return false;
}
// 查找某个元素对应的位置
public int indexOf(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if(this.elem[i] == toFind) {
return i;
}
}
return -1;
}
// 获取 pos 位置的元素
public int get(int pos) {
if(pos < 0 || pos >= this.usedSize) {
System.out.println("pos位置不合法!");
throw new RuntimeException("pos位置不合法!");
//return -1;//这里只是检查一下,实际业务处理,这里需要抛异常,自定义的异常
}
return this.elem[pos];
}
// 给 pos 位置的元素设为 value
public void set(int pos, int value) {
if(pos < 0 || pos >= this.usedSize) {
System.out.println("pos位置不合法!");
throw new RuntimeException("pos位置不合法!");
}
this.elem[pos] = value;
}
//删除第一次出现的关键字key
public void remove(int key) {
if(isEmpty()) {
System.out.println("空的 不能删除!");
return;
}
int index = indexOf(key);
for (int i = index; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
this.usedSize--;
//this.elem[this.usedSize] = null; 如果是引用数据类型,一定要置为空
}
public boolean isEmpty() {
if(this.usedSize == 0) {
return true;
}
return false;
}
// 获取顺序表长度
public int size() {
return this.usedSize;
}
// 清空顺序表
public void clear() {
this.usedSize = 0;
}
}
主函数代码(个别举例):
public class TestDemo {
public static void main(String[] args) {
ArrayList arrayList=new ArrayList();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.mytoString();
arrayList.isEmpty();
arrayList.remove(3);
System.out.println(arrayList.size());
arrayList.remove(3);
arrayList.mytoString();
}
}
举例运行结果: