数据结构<八>: 数组实现的线程表

package com.mo.object;

/**
 *  线程表-->顺序表的数据结构
 */
public interface List {
	/**
	 * 插入
	 */
	void insert(int i,Object obj)throws Exception;
	/**
	 * 删除
	 */
	Object delete(int i)throws Exception;
	/**
	 * 取数据元素
	 */
	Object getData(int i)throws Exception;
	/**
	 * 求元素个数
	 */
	int size();
	/**
	 * 是否空
	 */
	boolean isEmpty();
}


package com.mo.object;

/**
 *	这是一个数组实现的链表
 */
public class SeqList implements List {
	
	final int defaultSize = 10;//数组默认创建的长度
	int size;//数组的元素个数
	int maxSize;//数组的长度
	Object[] listArray;
	
	public SeqList() {
		init(defaultSize);
	}

	public SeqList(int maxSize) {
		init(maxSize);
	}

	/**
	 * 初始化数组对象
	 */
	private void init(int arrSize) {
		this.maxSize = arrSize;
		this.size = 0;
		this.listArray = new Object[arrSize];
	}
	
	public void insert(int i, Object obj) throws Exception {
		if(this.size == this.maxSize) {
			throw new Exception("数组已经满了,不能再插进元素了");
		}
		if(i < 0) {
			throw new Exception("输入的参数不能为零或者是负数");
		}
		if(i > this.maxSize) {
			throw new Exception("输出的参数不能大于该数组的长度");
		}
		for(int j = size; j > i; j--) {
			listArray[j] = listArray[j-1];
		}
		listArray[i] = obj;
		size++;
	}

	public Object delete(int i) throws Exception {
		if(size == 0) {
			throw new Exception("顺序表已经空了");
		}
		if(i < 0) {
			throw new Exception("输入的参数不能为负数或者是零");
		}
		if(i > maxSize) {
			throw new Exception("输入的参数不能大于数组的最大值");
		}
		Object obj = listArray[i];
		for(int j = i; j < size - 1; j++) {
			listArray[j] = listArray[j+1];
		}
		size--;
		return obj;
	}

	public Object getData(int i) {
		return listArray[i];
	}

	public int size() {
		return size;
	}

	public boolean isEmpty() {
		return size == 0;
	}
	
	public static void main(String[] args) throws Exception {
		SeqList arrList = new SeqList();
		for (int i = 0; i < 10; i++) {
			arrList.insert(i, "元素" + i);
		}
		System.out.println("size" + arrList.size());
		System.out.println("是否为空" + arrList.isEmpty());
		for(int j = 0; j<10; j++) {
			System.out.print("取出元素" + arrList.getData(j));
		}
		System.out.println();
		for(int i = 0; i < 10; i++) {
			System.out.print("删除元素" + arrList.delete(i));
		}
		System.out.println();
		System.out.println("size" + arrList.size());
		System.out.println("是否为空" + arrList.isEmpty());
	}
	
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值