线性表的顺序结构和链式结构C++代码例子
时间: 2025-01-05 17:40:43 浏览: 3
线性表的数据结构主要有顺序存储(数组)和链接存储(链表)。这里分别给出C++的简单例子。
**顺序结构(数组):**
```cpp
#include <iostream>
using namespace std;
// 定义数组
template <typename T>
class ArrayLinearList {
private:
T* data; // 数据指针
int size;
public:
ArrayLinearList(int capacity) : size(0), data(new T[capacity]) {}
~ArrayLinearList() { delete[] data; } // 析构函数释放内存
void push_back(T value) {
if (size == data->size) resize(size * 2); // 当满时扩大容量
data[size++] = value;
}
void print_list() {
for (int i = 0; i < size; i++) {
cout << data[i] << " ";
}
cout << endl;
}
private:
void resize(int new_capacity) {
T* newData = new T[new_capacity];
for (int i = 0; i < size; i++)
newData[i] = data[i];
delete[] data;
data = newData;
}
};
int main() {
ArrayLinearList<int> list(5);
list.push_back(10);
list.push_back(20);
list.print_list(); // 输出:10 20
return 0;
}
```
**链式结构(链表):**
```cpp
#include <iostream>
using namespace std;
// 链表节点
template <typename T>
struct ListNode {
T value;
ListNode<T>* next;
ListNode(T val) : value(val), next(nullptr) {} // 构造函数
};
// 链表类
template <typename T>
class LinkedList {
private:
ListNode<T>* head;
public:
LinkedList() : head(nullptr) {}
void append(T value) {
ListNode<T>* newNode = new ListNode<T>(value);
if (!head)
head = newNode;
else {
ListNode<T>* current = head;
while (current->next)
current = current->next;
current->next = newNode;
}
}
void print_list() {
ListNode<T>* temp = head;
while (temp) {
cout << temp->value << " -> ";
temp = temp->next;
}
cout << "nullptr" << endl;
}
};
int main() {
LinkedList<int> list;
list.append(10);
list.append(20);
list.print_list(); // 输出:10 -> 20 -> nullptr
return 0;
}
```
阅读全文