/**
*
* 线性顺序表
*/
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();
}
}
转载于:https://my.oschina.net/u/2360415/blog/539859