Code table for linear arrays

Table linear array manner

//数组方式实现线性表
class ArrayList{
	
	/*
		数据部分
		一个数组和一个标识长度的值
	*/
	private Object[] arr;
	private int length;
	
	//无参构造函数
	public ArrayList(){
		length = 20;
		arr = new Object[20];
	}
	
	//构造指定长度的线性表
	public ArrayList(int len){
		length = len;
		arr = new Object[len + 20];
	}
	
	public ArrayList(Object[] objs){
		this.length = objs.length;
		arr = objs;
	}
	
	//在列表末尾追加元素
	public void append(Object obj){
		if(arr.length > this.length){
			
			arr[length] = obj;
			
		}else{
			
			Object[] temp = new Object[arr.length + 100];
			
			for(int i = 0;i < length;i++){
				temp[i] = arr[i];
			}
			temp[length] = obj;
			arr = temp;
		}
		length++;
	}
	
	//在指定位置插入元素
	public void insert(int pos, Object obj){
		try{
			if(arr.length > this.length){
				if(pos >= length){
					throw new Exception("位置输入错误");
				}else{
					for(int i = this.length;i >= pos;i--){
						arr[i] = arr[i - 1];
					}
					arr[pos] = obj;
				}
			}else{
				if(pos >= length){
					throw new Exception("位置输入错误");
				}else{
					Object[] temp = new Object[arr.length + 100];
					for(int i = 0;i < length;i++){
						temp[i] = arr[i];
					}
					arr = temp;
					for(int i = this.length;i >= pos;i--){
						arr[i] = arr[i - 1];
					}
					arr[pos] = obj;
				}
			}
			this.length++;
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	//删除指定位置元素
	public void delete(int index){
		try{
			if(index > this.length){
				throw new Exception("输入位置有误");
			}else{
				for(int i = index;i < this.length - 1;i++){
					arr[i] = arr[i + 1];
				}
				arr[length - 1] = null;
				this.length--;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	//替换指定位置元素
	public void replace(int pos, Object obj){
		try{
			if(pos >= length){
				throw new Exception("输入的位置有误");
			}else{
				arr[pos] = obj;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	//判断是否为空
	public boolean isEmpty(){
		return length == 0?true:false;
	}
	//返回长度
	public int getLength(){
		return this.length;
	}
	//获取某个位置上的元素
	public Object get(int index){
		
		Object obj = null;
		
		try{
			if(index >= length){
				throw new Exception("输入的位置有误");
			}else{
				obj = arr[index];
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return obj;
		
	}
	//遍历线性表 返回表中元素
	public void printArr(){
		System.out.print("{ ");
		for(int i = 0;i < length;i++){
			if(i == length - 1){
				System.out.print(arr[i] + " }\n");
			}else{
				System.out.print(arr[i] + ",");
			}
		}
	}
	
}
Released six original articles · won praise 0 · Views 113

Guess you like

Origin blog.csdn.net/AC_sunK/article/details/104116564