顺序表
- 顺序表其实就是一个写到类中的数组。写到类中就可以面向对象了。实现增删改查。
- 顺序表特点
- 物理上和逻辑上都是连续的
- 插入和删除元素,必须移动元素。(时间复杂度:O(N))
- 扩容也是问题
- 可以实现随机读取(查找时间复杂度:O(1))
- 顺序表的代码目录
public class SeqList {
public void display() { }
public void add(int pos, int data) { }
public boolean contains(int toFind) { return true; }
public int search(int toFind) { return -1; }
public int getPos(int pos) { return -1; }
public void setPos(int pos, int value) { }
public void remove(int toRemove) { }
public int size() { return 0; }
public void clear() { }
}
- 顺序表类的具体代码实现:
public class MyArrayList {
public int[] elem;
public int usedSize;
public MyArrayList() {
this.elem = new int[10];
}
public void display() {
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i] + " ");
}
System.out.println();
}
public int size() {
return this.usedSize;
}
public boolean isFull() {
if (this.usedSize == this.elem.length) {
return true;
}
return false;
}
public void add(int pos, int data) {
if (pos < 0 || pos > usedSize) {
System.out.println("pos 位置不合法!");
return;
}
if (this.isFull()) {
this.elem = Arrays.copyOf(this.elem, 2*this.elem.length);
}
for (int i = this.usedSize-1; i >= pos; i++) {
this.elem[i+1] = this.elem[i];
}
this.elem[pos] = data;
usedSize++;
}
public boolean contains(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if (this.elem[i] == toFind) {
return true;
}
}
return false;
}
public int search(int toFind) {
for (int i = 0; i < this.usedSize; i++) {
if (this.elem[i] == toFind) {
return i;
}
}
return -1;
}
public boolean isEmpty() {
return this.usedSize == 0;
}
public int getPos(int pos) {
if (pos < 0 || pos >= this.usedSize) {
System.out.println("pos 位置不合法!");
return -1;
}
if (isEmpty()) {
return -1;
}
return this.elem[pos];
}
public void setPos(int pos, int value) {
if (pos < 0 || pos >= this.usedSize) {
System.out.println("pos位置不合法");
return;
}
if (isEmpty()) {
System.out.println("顺序表为空!");
return;
}
this.elem[pos] = value;
}
public void remove(int toRemove) {
if (isEmpty()) {
System.out.println("顺序表为空");
return;
}
int index = this.search(toRemove);
if (index == -1) {
System.out.println("没有要找的数字!");
return;
}
for (int i = index; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
this.usedSize -= 1;
}
public void clear() {
this.usedSize = 0;
}
}