顺序表(SequenceList)
import java.util.Arrays;
/**
* JAVA实现顺序表
*/
public class MyArrayList {
public int[] elem; //顺序表元素
public int usedSize;//顺序表实际大小
public MyArrayList() {
this.elem = new int[10];
}
// 打印顺序表
public void display() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i]+" ");
}
System.out.println();
}
//判断顺序表是否填满
public boolean is_Full(){
return this.usedSize == this.elem.length;
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
if(pos < 0 || pos > this.usedSize){
System.out.println("pos位置不合适!!");
return ;
}
if(is_Full()){
this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
}
for (int i = 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-1; i++) {
if(toFind == this.elem[i]){
return true;
}
}
return false;
}
// 查找某个元素对应的位置
public int search(int toFind) {
for (int i = 0; i < this.usedSize-1; i++) {
if(toFind == this.elem[i]){
return i;
}
}
return -1;
}
// 获取 pos 位置的元素
public int getPos(int pos) {
if(pos < 0 || pos > this.usedSize){
System.out.println("pos位置不合适!!");
return -1;
}
for (int i = 0; i < this.usedSize-1; i++) {
if(i == pos){
return this.elem[pos];
}
}
return -1;
}
// 给 pos 位置的元素设为 value
public void setPos(int pos, int value) {
if(pos < 0 || pos > this.usedSize){
System.out.println("pos位置不合适!!");
}
for (int i = 0; i < this.usedSize-1; i++) {
if(i == pos){
this.elem[pos] = value;
}
}
}
//删除第一次出现的关键字key
public void remove(int toRemove) {
int indes = search(toRemove);
if(indes == -1){
System.out.println("没有你要删除的元素");
}
for (int i = indes; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
this.usedSize--;
}
// 获取顺序表长度
public int size() {
return this.usedSize;
}
// 清空顺序表
public void clear() {
this.usedSize =0;
}
public static void main(String[] args) {
MyArrayList myArrayList = new MyArrayList();
myArrayList.display();
//在零位置增加元素
myArrayList.add(0,1);
myArrayList.add(0,2);
myArrayList.add(0,3);
myArrayList.add(0,4);
myArrayList.add(0,5);
myArrayList.add(0,6);
myArrayList.add(0,7);
myArrayList.display();
boolean falg = myArrayList.contains(5);
System.out.println(falg);
int ret = myArrayList.search(5);
System.out.println(ret);
int ret2 =myArrayList.getPos(2);
System.out.println(ret2);
myArrayList.setPos(2,10);
myArrayList.display();
myArrayList.remove(10);
myArrayList.display();
}
}
Last updated