java實現線性順序表

/**
 * 
 * 線性順序表
 */
public class SequentialLinearList {

 private char[] list;
 private int length;// 實際長度
 private int size;// 容量

 /**
  * 初始化順序表,長度爲length
  */
 public SequentialLinearList(int size) {
 this.size = size;

 length = 0;
 list = new char[size];
 }

 /**
  * 將index位置賦值爲c,會覆蓋掉原值
  * 
  * @param index
  * @param c
  */
 public void set(int index, char c) {
 if (index > size - 1 || index < 0) {
 System.out.println("out of size exception!");
 return;
 } else {
 if (get(index) == 0)
 length++;
 list[index] = c;
 }
 }

 /**
  * 取得下標爲index的值,若是爲空返回ascii爲零的字符
  * 
  * @param index
  * @param c
  * @return
  */
 public char get(int index) {
 if (index > size - 1 || index < 0) {
 System.out.println("out of size exception!");
 return 0;
 } else {
 return list[index];
 }
 }

 /**
  * 在index位置插入c,不會覆蓋掉原值
  * 
  * @param index
  * @param c
  */
 public void insert(int index, char c) {
 if (index > size - 1 && index < 0) {
 System.out.println("out of size exception!");
 return;
 } else if (length >= size) {
 System.out.println("insert into full list exception!");
 return;
 } else if (get(index) == 0) {
 set(index, c);
 } else {
 for (int i = length - 1; i >= index; i--) {
 list[i + 1] = list[i];
 }
 set(index, c);
 length++;
 }
 }

 /**
  * 返回長度
  * 
  * @return
  */
 public int length() {
 return length;
 }

 /**
  * 刪除下標爲index的元素
  * 
  * @param index
  */
 public void delete(int index) {
 if (index > length - 1 || index < 0) {
 System.out.println("delete not exist element exception");
 } else {
 for (int i = index; i < length - 1; i++) {
 list[i] = list[i + 1];
 }
 list[length - 1] = 0;
 length--;
 }
 }

 /**
  * 查找c元素,返回第一個找的c元素的下標,沒有找到返回-1
  * 
  * @param c
  */
 public int findChar(char c) {
 for (int i = 0; i < length; i++) {
 if (list[i] == c) {
 return i;
 }
 }
 return -1;
 }

 public void show() {
 for (int i = 0; i < length; i++) {
 System.out.print(list[i] + ",");
 }
 System.out.println();
 }

 public static void main(String[] args) {
 SequentialLinearList sll = new SequentialLinearList(10);
 sll.set(0, 'a');
 sll.set(1, 'b');
 sll.set(2, 'c');
 sll.set(3, 'd');
 sll.set(4, 'e');
 sll.show();
 sll.insert(2, 'f');
 sll.show();
 sll.delete(2);
 sll.show();
 System.out.println(sll.length());
 System.out.println(sll.findChar('c'));
 sll.set(0, 'z');
 sll.show();
 }

}
相關文章
相關標籤/搜索