算法初級(三)——線性表

概念:
線性表是由n(n \geq 0)個數據元素所構成的有限序列,通常表示爲(a0a_0,a1a_1,a2a_2,a3a_3an1a_{n-1}),其中下標i標識數據元素在線性表中的序列號,n爲線性表長(n=0爲空表)。對於同一個線性表,其每一個數據元素的值雖然不同但是卻具有相同的數據類型,同時數據元素之間具有一種線性的或“一對一”的邏輯關係,即:

  • 第一個數據元素沒有前驅,這個數據元素稱爲開始結點;
  • 最後一個數據元素沒有後繼,這個數據元素稱爲終端節點;
  • 除了第一個和最後一個數據元素外,其他數據元素有且僅有一個前驅和後繼。

圖示:
在這裏插入圖片描述
線性表結構簡單,一般來說有以下幾種主要操作:

  1. 置空操作clear()
  2. 判空操作isEmpty()
  3. 獲取長度length()
  4. 獲取元素get(i)
  5. 插入元素insert(index,object)
  6. 刪除操作remove(i)
  7. 查找操作indexOf(i)
  8. 輸出display()

用java的抽象數據類型寫下代碼:

interface IList{
	public void clear();
	public boolean isEmpty();
	public int length();
	public Object get(int i);
	public void insert(int index,Object object);
	public void remove(int i);
	public void indexOf(Object object);
	public void display();
}

加上實現方法:

interface IList {
	public void clear();

	public boolean isEmpty();

	public int length();

	public Object get(int i) throws Exception;

	public void insert(int index, Object object) throws Exception;

	public void remove(int i) throws Exception;

	public int indexOf(Object object);

	public void display();
}

public class MyList implements IList {
	private Object[] listElem;// 線性表的存儲空間
	private int curLen;// 線性表當前長度

	public MyList(int maxSize) {
		listElem = new Object[maxSize];// 分配大小爲maxSize的存儲單元
		curLen = 0;// 置順序表的當前長度爲0
	}

	@Override
	public void clear() {
		// 置順序表當前的長度爲0
		curLen = 0;// 置順序表的當前長度爲0,這裏沒有釋放內存,把listElem == null
	}

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

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

	@Override
	public Object get(int i) throws Exception {
		if (i < 0 || i > curLen - 1)
			throw new Exception("下標異常");
		return listElem[i];
	}

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

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

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

	@Override
	public void display() {
		for (int i = 0; i < listElem.length; i++) {
			System.out.println(listElem);
		}
	}

}

先到這,告辭!

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