// 判断线性表是否为空 publicbooleanisEmpty() { return len == 0; }
// 判断线性表是否已满 publicbooleanisFull() { return len == maxSize; }
// 获取线性表的长度 publicintlength() { return len; }
// 获取第 i 个位置的元素 public E get(int i) { if (i < 0 || i >= len) { thrownewIndexOutOfBoundsException("Index: " + i + ", Size: " + len); } return elem[i]; }
// 查找值等于 e 的元素的索引,不存在返回 -1 publicintfind(E e) { for (inti=0; i < len; i++) { if (elem[i].equals(e)) { return i; } } return -1; }
// 在第 i 个位置插入元素 e publicvoidinsert(int i, E e) { if (isFull()) { expandCapacity(); } if (i < 0 || i > len) { thrownewIndexOutOfBoundsException("Index: " + i + ", Size: " + len); } // 将第 i 位及以后的元素后移 for (intj= len; j > i; j--) { elem[j] = elem[j - 1]; } elem[i] = e; len++; }
// 删除第 i 个位置的元素,并返回其值 public E remove(int i) { if (i < 0 || i >= len) { thrownewIndexOutOfBoundsException("Index: " + i + ", Size: " + len); } EremovedElement= elem[i]; // 将第 i+1 位及以后的元素前移 for (intj= i; j < len - 1; j++) { elem[j] = elem[j + 1]; } len--; return removedElement; }
// 获取第 i 个位置的元素 T get(int i)const{ if (i < 0 || i >= size) { throw std::out_of_range("Index out of range"); } Node* current = head; for (int j = 0; j < i; ++j) { current = current->next; } return current->data; }
// 查找值等于 e 的元素的索引,不存在返回 -1 intfind(const T& e)const{ Node* current = head; int index = 0; while (current != nullptr) { if (current->data == e) { return index; } current = current->next; ++index; } return-1; }
// 在第 i 个位置插入元素 e voidinsert(int i, const T& e){ if (i < 0 || i > size) { throw std::out_of_range("Index out of range"); } if (i == 0) { head = newNode(e, head); // 插入到头部 } else { Node* current = head; for (int j = 0; j < i - 1; ++j) { current = current->next; } current->next = newNode(e, current->next); // 插入到中间或尾部 } ++size; }
// 在链表末尾添加元素 e voidadd(const T& e){ if (head == nullptr) { head = newNode(e); } else { Node* current = head; while (current->next != nullptr) { current = current->next; } current->next = newNode(e); } ++size; }
// 删除第 i 个位置的元素,并返回其值 T remove(int i){ if (i < 0 || i >= size) { throw std::out_of_range("Index out of range"); } Node* toDelete; T removedElement; if (i == 0) { toDelete = head; removedElement = head->data; head = head->next; // 删除头部节点 } else { Node* current = head; for (int j = 0; j < i - 1; ++j) { current = current->next; } toDelete = current->next; removedElement = toDelete->data; current->next = toDelete->next; // 删除中间或尾部节点 } delete toDelete; --size; return removedElement; }