21xrx.com
2025-03-31 00:03:43 Monday
文章检索 我的文章 写文章
C++ 线性表代码实现
2023-07-08 15:21:54 深夜i     22     0
C++编程语言 线性表数据结构 代码实现 链表 数组

C++ 线性表是一种数据结构,它允许我们通过一种有序的方式来存储信息,并且通过一定的方式来访问和修改这些信息。在本文中,我们将介绍如何在C++中实现线性表,并提供一个基本的实例代码。

实现线性表的关键是定义一个可以存储数据的数据结构。我们可以使用一个数组来实现它,这个数组的长度应该足够存储我们需要存储的数据。

下面是一个简单的代码实现:

#define MAX_SIZE 100
template <typename T>
class LinearList {
private:
  T data[MAX_SIZE];
  int length;
public:
  LinearList();
  ~LinearList();
  void clear();
  bool isEmpty() const;
  int size() const;
  T& operator[](const int& i);
  T operator[](const int& i) const;
  int find(const T& x) const;
  void insert(const int& i, const T& x);
  void remove(const int& i);
  void display() const;
};
template <typename T>
LinearList<T>::LinearList() {
  length = 0;
}
template <typename T>
LinearList<T>::~LinearList() {
}
template <typename T>
void LinearList<T>::clear() {
  length = 0;
}
template <typename T>
bool LinearList<T>::isEmpty() const {
  return length == 0;
}
template <typename T>
int LinearList<T>::size() const {
  return length;
}
template <typename T>
T& LinearList<T>::operator[](const int& i) {
  return data[i];
}
template <typename T>
T LinearList<T>::operator[](const int& i) const {
  return data[i];
}
template <typename T>
int LinearList<T>::find(const T& x) const {
  for (int i = 0; i < length; i++) {
    if (data[i] == x) {
      return i;
    }
  }
  return -1;
}
template <typename T>
void LinearList<T>::insert(const int& i, const T& x) {
  if (length == MAX_SIZE) {
    cout << "List is full!" << endl;
    return;
  }
  if (i < 0 || i > length) {
    cout << "Index out of range!" << endl;
    return;
  }
  for (int j = length; j > i; j--) {
    data[j] = data[j - 1];
  }
  data[i] = x;
  length++;
}
template <typename T>
void LinearList<T>::remove(const int& i) {
  if (isEmpty()) {
    cout << "List is empty!" << endl;
    return;
  }
  if (i < 0 || i > length - 1) {
    cout << "Index out of range!" << endl;
    return;
  }
  for (int j = i; j < length - 1; j++) {
    data[j] = data[j + 1];
  }
  length--;
}
template <typename T>
void LinearList<T>::display() const {
  for (int i = 0; i < length; i++) {
    cout << data[i] << " ";
  }
  cout << endl;
}

此代码实现了一个线性表的基本操作:清除列表、检查列表是否为空、获取列表大小、按索引获取或修改元素、查找元素的位置、插入元素及删除元素。

尽管上述实现非常基础,但它提供了一个简单的框架,以便我们能够扩展这个数据结构,并实现更复杂的操作。通过这个实例代码,我们可以更进一步学习线性表的相关知识。

  
  

评论区

请求出错了