java实现顺序表

     顺序表是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构。线性表采用顺序存储的方式存储就称之为顺序表。顺序表是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中。

1,创建一个顺序表        

               

class TestSqlist{
	int usedSize;//顺序表实际长度
	int[] elem;//数组
	public TestSqlist(){
		this(10);
	}
	
	public TestSqlist(int size){
		elem = new int[size];
		usedSize = 0;
	}
}


2,判断顺序表是否为满

public boolean isFull(){
		if(usedSize == elem.length){
			return true;
		}else{
			return false;
		}
	}

3,插入数据

1>数组已满返回false

public boolean insert(int val,int pos){
		if(isFull() || pos < 0 || pos > this.usedSize){
			return false;
		}
		for(int i = this.usedSize-1;i >= pos;i--){//从后向前来依次挪动
			elem[i+1] = elem[i]; 
		}
		elem[pos] = val;
		this.usedSize++;
		return true;
	}

2>数组已满对数组进行扩容

使用Arrays.copyOf()进行扩容


public boolean insert(int val,int pos){
		if(isFull()){
			elem = Arrays.copyOf(elem, elem.length+10);
		}
		if(pos < 0 || pos > this.usedSize){
			return false;
		}
		for(int i = this.usedSize-1;i >= pos;i--){//从后向前来依次挪动
			elem[i+1] = elem[i]; 
		}
		elem[pos] = val;
		this.usedSize++;
		return true;
	}

4,判断顺序表是否为空

public boolean isEmpty(){
		if(this.usedSize == 0){
			return true;
		}
		return false;
	}

5,查找关键字key,返回下标

public int search(int key){
		//存在顺序表为空
		if(isEmpty()){
			return -1;
		}
		int pos = -1;
		for(int i = 0;i < this.usedSize;i++){
			if(elem[i] == key){
				pos = i;
			}
		}
		return pos;
	}

6,删除元素

public void delete(int val){
		int pos = search(val);
		if(pos == -1){
			System.out.println("无指定元素");
		}else{
			for(int i = pos;i < this.usedSize-1;i++){
				elem[i] = elem[i+1];
			}
			this.usedSize--;
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_37937537/article/details/80187846