大家好,今天我们练习一下顺序表的一些操作;
顺序表是基于数组的,所以我们要定义一MyArarry类,int[ ] , usesize
import java.util.ArrayList;
import java.util.Arrays;
public class MyArrayList {
public int[] elem;
private int usedsize;
public MyArrayList() {
this.elem = new int[10];
}
public MyArrayList(int n) {
this.elem = new int[n];
}
//扩容
public void kuorong(){
this.elem=Arrays.copyOf(this.elem,2*this.elem.length);
}
//判断是不是满了
public boolean isFull(){
if (this.usedsize==this.elem.length){
return true;
}
return false;
}
public void display(){
for(int i=0;i<=this.usedsize;i++){
System.out.printf(this.elem[i]+" ");
}
System.out.println();
}
//在给定位置添加数据
public void add(int pos,int data) {
if (isFull() == true) {
System.out.println("表已经满了,开始扩容");
kuorong();
}
if (pos < 0 || pos > this.usedsize) {
System.out.printf("pos不合法");
return;
}
for (int i = this.usedsize - 1; i >= pos; i--) {//开始移动元素
this.elem[i + 1] = this.elem[i];
}
this.elem[pos] = data;
this.usedsize++;
}
//默认插入顺序表(从后)
public void add1(int data){
if (isFull()==true){
System.out.printf("表已经满了,开始扩容");
kuorong();
}
this.elem[usedsize]=data;
usedsize++;
}
//判断是不是包含一个给定的数
public boolean isFound(int n){
for (int i=0;i<=this.usedsize;i++){
if (this.elem[i]==n){
return true;
}
}
return false;
}
//获取长度
public int size(){
return this.usedsize;
}
//获取pos位置的元素
public int getPos(int pos){
if (pos<0||pos>=this.usedsize){
return -1;
}
return this.elem[pos];
}
//把给定pos位置上的数变成valse
public int posValse(int pos,int valse){
if (pos<0||pos>=this.usedsize){
System.out.println("pos不合法");
return -1;
}
this.elem[pos]=valse;
return this.elem[pos];
}
//查找某个·元素对应的位置
public int search(int toFind){
for(int i=0;i<this.usedsize;i++){
if (this.elem[i]==toFind){
return i;
}
}
return -1;
}
//删除第一次出现的关键字KEY;
public void remore(int key){
int index=search(key);
if(index==-1){
System.out.printf("没有第二个");
return;
}
for (int i=index;i<this.usedsize-1;i++){
this.elem[i]=this.elem[i+1];
}
this.usedsize--;
}
//清空顺序表
public void clear(){
this.usedsize=0;
}
}
import java.util.ArrayList;
public class TestDemolist {
public static void main(String[] args) {
MyArrayList myArrayList=new MyArrayList(10);
myArrayList.add1(11);
myArrayList.add1(22);
myArrayList.add1(1445);
myArrayList.add1(133);
myArrayList.add(0,666);
myArrayList.isFound(22);
boolean n=myArrayList.isFound(22);
System.out.println(n);
int sum=myArrayList.size();
System.out.println(sum);
myArrayList.display();
}
}

java&spm=1001.2101.3001.5002&articleId=112192142&d=1&t=3&u=25a5f2cb6d0447f780905d85fb316bdd)
1617

被折叠的 条评论
为什么被折叠?



