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、易造成存儲空間的“碎片”。

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