1. 程式人生 > >資料結構與演算法——線性表之順序表(JAVA語言實現 )

資料結構與演算法——線性表之順序表(JAVA語言實現 )

資料結構與演算法——線性表之順序表(JAVA語言實現 )


線性表是由n個數據元素組成的優先序列。

線性表中每個元素都必須有相同的結構,線性表是線性結構中最常用而又最簡單的一種資料結構。線性表由儲存結構是否連續可分為順序表和連結串列。順序表指線性表中每個元素按順序依次儲存,線性表中邏輯上相鄰的兩個元素其在記憶體中的地址也是相鄰的。而連結串列指的是每個資料元素儲存不一定連續的一種資料結構,即鏈式儲存。從記憶體中的分佈來說,下一個元素的地址在與其相鄰的上一個節點中儲存,即連結串列每個節點的值由兩部分組成,一部分是資料域,另一部分存一個引用(即指標,或者說是一個地址),指向該節點的下一個節點。

下面的程式碼是一個簡單的順序結構線性表的原始碼,這個類部分實現了ArrayList的功能。



public class SequenceList<T> {
	private int DEFAULT_SIZE = 10;	//線性表中最大元素個數
	private int capacity;			//儲存陣列長度
	private Object[] elementData;
	private int size = 0;
	
	public SequenceList() {
		capacity = DEFAULT_SIZE;
		elementData = new Object[capacity];
	}
	
	//以初始化元素建立順序線性表
	public SequenceList(int 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;
	}
	
	//獲取表中下標為i的元素值
	public T getData(int i) {
		if(i < 0 || i > size) {
			throw new IndexOutOfBoundsException("線性表索引越界");
		}
		return (T)elementData[i];
	}
	
	//順序表的查詢(查詢索引)
	public int search(T data) {
		for(int i = 0;i < size;i++) {
			if(elementData[i] == data) {
				return i;
			}
		}
		System.out.println("Not found!!!");
		return -1;
	}
	
	//向線性表中下標為index的地方插入一個元素
	public void insert(T data,int index) {
		if(index < 0 || index >size) {
			throw new IndexOutOfBoundsException("線性表索引越界");
		}
		if(size > DEFAULT_SIZE) {
			System.out.println("順序表中元素個數已達上限,不能再插入資料");
			return;
		}
		//插入操作
		System.arraycopy(elementData, index, elementData, index+1, size-index);
		elementData[index] = data;
		size++;
	}
	
	//在表的末尾插入元素
	public void addElement(T data) {
		insert(data,size);
	}
	//刪除表中指定索引處的元素
	public void delete(int index) {
		if(index < 0 || index >size) {
			throw new IndexOutOfBoundsException("線性表索引越界");
		}
		T t = (T)elementData[index];
		int num = size-index-1;
		if(num > 0) {
			System.arraycopy(elementData, index+1, elementData, index, num);
		}
		size--;
		System.out.println("刪除成功");
	}
	
	
	//判斷表是否為空
	public boolean isEmpty() {
		return size == 0;
	}
	
	//清空線性表
	public void makeEmpty() {
		size = 0;
	}

}



測試程式碼:

public class Test {
	public static void main(String[] args) {
		SequenceList<String> stringList = new SequenceList<String>();
		
		stringList.addElement("111");
		stringList.addElement("222");
		stringList.addElement("444");
		
		stringList.insert("333", 2);
		
		for(int i=0;i<stringList.length();i++) {
			System.out.print(stringList.getData(i)+" ");
		}
		System.out.println();
		
		System.out.println("元素“111”在順序表中的下標為 :"+stringList.search("111"));
	}
}