线性表的顺序存储

线性表基本特征:
    唯一的第一个元素;
    唯一的最后一个元素;
    除第一个元素外都只有一个前驱元素;
    除最后一个元素外都只有一个后继元素。

package 线性表;

import java.util.Arrays;

public class SequenceList<T> {
	private int DEFAULT_SIZE=16;
	private int capacity;
	private Object[]elementData;
	private int size=0;
	public SequenceList(){
		capacity=DEFAULT_SIZE;
		elementData=new Object[capacity];
	}
	public SequenceList(T element){
		this();
		elementData[0]=element;
		size++;
	}
	public SequenceList(T element,int initSize){
		capacity=1;
		while(capacity<initSize){
			capacity<<=1;
		}
		elementData=new Object[capacity];
		elementData[0]=element;
		size++;
	}
	public int length(){
		return size;
	}
	public T get(int i){
		if(i<0||i>size-1){
			throw new IndexOutOfBoundsException("线性表索引越界");
		}
		return (T)elementData[i];
	}
	public int locate(T element){
		for(int i=0;i<size;i++){
			if(elementData[i].equals(element)){
				return i;
			}
		}
		return -1;
	}
	public void insert(T element,int index){
		if(index<0||index>size){
			throw new IndexOutOfBoundsException("线性表索引越界");
		}
		ensureCapacity(size+1);
		System.arraycopy(elementData, index, element, index+1, size-index);
		elementData[index]=element;
		size++;
	}
	public void add(T element){
		insert(element,size);
	}
	public void ensureCapacity(int minCapacity){
		if(minCapacity>capacity){
			while(capacity<minCapacity){
				capacity<<=1;
			}
			elementData=Arrays.copyOf(elementData, capacity);
		}
	}
	public T delete(int index){
		if(index<0||index>size-1){
			throw new IndexOutOfBoundsException("线性表索引越界");
		}
		T oldValue=(T)elementData[index];
		int numMoved=size-index-1;
		if(numMoved>0){
			System.arraycopy(elementData, index+1, elementData, index, numMoved);
			
		}
		elementData[--size]=null;
		return oldValue;
	}
	
	public T remove(){
		return delete(size-1);
	}
	public boolean empty(){
		return size==0;
	}
	public void clear(){
		Arrays.fill(elementData, null);
		size=0;
	}
	public String toString(){
		if(size==0){
			return "[]";
		}else{
			StringBuilder sb=new StringBuilder("[");
			for(int i=0;i<size;i++){
				sb.append(elementData[i].toString()+",");
			}
			int len=sb.length();
			return sb.delete(len-2, len).append("]").toString();
		}
	}
	
	

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值