java实现线性表的顺序存储操作

新建一个接口:IList,定义操作:

package com.list;

public interface IList {

	public void clear();	//清空线性表
	
	public boolean isEmpty();
	
	public int length();	//获取元素个数
	
	public Object get(int i) throws Exception;	//获取第 i+1 个元素,i从0开始
	
	public void insert(int i, Object x) throws Exception;
	
	public void remove(int i) throws Exception;
	
	public int indexOf(Object x);
	
	public void display();
}

新建一个SqList类实现IList接口的方法:

package com.list;

public class SqList implements IList {

	public Object[] listElem;	//线性表存储空间
	public int curLength;		//线性表当前长度
	
	public SqList(int maxSize) {
		curLength = 0;
		listElem = new Object[maxSize];
	}
	
	@Override
	public void clear() {
		curLength = 0;
	}

	@Override
	public boolean isEmpty() {
		return curLength == 0;
	}

	@Override
	public int length() {
		return curLength;
	}

	@Override
	public Object get(int i) throws Exception {
		if (curLength == 0) {
			throw new Exception("当前线性表为空 --> " + curLength);
		}
		if (i < 0 || i >= curLength) {
			throw new Exception("第" + i + "个元素不存在");
		}
		return listElem[i];
	}

	@Override
	public void insert(int i, Object x) throws Exception {
		if (curLength == listElem.length) {
			throw new Exception("顺序表已满");
		}
		if (i < 0 || i >= listElem.length) {
			throw new Exception("插入位置不合法");
		}
		for (int j = curLength; j > i; j--) {
			listElem[j] = listElem[j - 1];
		}
		listElem[i] = x;
		curLength++;
	}

	@Override
	public void remove(int i) throws Exception {
		if (i < 0 || i >= curLength) {
			throw new Exception("删除位置不合法");
		}
		for (int j = i; j < curLength - 1; j++) {
			listElem[j] = listElem[j + 1];
		}
		curLength--;
	}

	@Override
	public int indexOf(Object x) {
		int j = 0;
		
		while (j < curLength && !listElem[j].equals(x)) {
			j++;
		}
		if (j < curLength) {
			return j;
		}else {
			return -1;
		}
	}

	@Override
	public void display() {
		for (int j = 0; j < curLength; j++) {
			System.err.println(listElem[j]);
		}
	}
	
	public static void main(String[] args) {
		SqList list = new SqList(10);
		
		try {
			list.insert(0, 1);
			list.insert(0, 2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		list.display();
	}

}

线性表顺序存储的总结:

    优点:

    1、无需为表示元素之间的关系而增加额外的存储空间;

    2、可以快速的存取表中任一位置的元素。(时间复杂度为O(1))

    缺点:

    1、插入和删除操作需要移动大量的元素;(时间复杂度为O(N))

    2、当线性表长度变化较大时,无法确定存储空间容量;

    3、易造成存储空间的“碎片”。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章