数据结构:线性表的顺序存储--Java实现

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() {
		elementData = new Object[DEFAULT_SIZE];
		capacity = DEFAULT_SIZE;
	}

	// 存储数组长度不足时,数组拓展
	private void ensure(int oldsize) {
		if (oldsize > capacity) {
			while (capacity < oldsize) {
				capacity <<= 1;
			}
			elementData = Arrays.copyOf(elementData, capacity);
		}
	}

	// 以某元素初始化存储数组
	public SequenceList(T elemenT) {
		this();
		elementData[0] = elemenT;
		size++;
	}

	// 以某元素及指定长度初始化存储数组
	public SequenceList(T element, int initsize) {
		capacity = initsize;
		elementData = new Object[initsize];
		elementData[0] = element;
		size++;
	}

	// 获取线性表长度
	public int length() {
		return size;
	}

	// 获取线性表是否为空
	public boolean empty() {
		return size == 0;
	}

	// 获取指定索引的元素
	public T get(int i) {
		if (i > size - 1 || i < 0) {
			throw new RuntimeException("索引越界");
		}
		return (T)elementData[i];
	}

	// 查找线性表中的元素位置
	public int contains(T key) {
		for (int i = 0; i < size; i++) {
			if (elementData[i].equals(key)) {
				return i;
			}
		}
		return -1;
	}

	// 向线性表中添加元素
	public void add(T element) {
		Insert(element, size);
	}

	// 想存储数组中指定位置插入元素
	public void Insert(T element, int index) {
		if (index > size || index < 0) {
			throw new IndexOutOfBoundsException("不存在该位置");
		}
		ensure( size + 1);
		System.arraycopy(element, index, element, index + 1, size - index);
		elementData[index] = element;
		size++;
	}

	// 删除最后一个元素
	public T remove() {
		return delete(size - 1);

	}

	// 删除指定位置元素
	public T delete(int index) {
		if (index < 0 || index > size - 1) {
			throw new IndexOutOfBoundsException("线性表越界");
		}
		T oldValue = (T)elementData[index];
		elementData[index] = null;
		int key = size - index - 1;
		if (key > 0) {
			System.arraycopy(elementData, index + 1, elementData, index, key);
		}
		return oldValue;
	}

	// 线性表清空
	public void clear() {
		Arrays.fill(elementData, null);

	}

	// 输出
	public String toString() {
		if (size == 0) {
			return null;
		} else {
			StringBuilder str = new StringBuilder();
			str.append("[");
			for (int i = 0; i < size; i++) {
				str.append(elementData[i] + ",");
			}
			str.append("]");
			return str.toString();
		}
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值