【C++修炼之路】list 模拟实现
发布人:shili8
发布时间:2025-01-18 04:52
阅读次数:0
**C++修炼之路**
在 C++ 的世界里,链表(List)是一个非常重要的数据结构。它可以用来存储一系列的元素,而这些元素之间没有固定顺序。这使得链表成为一个非常灵活和高效的数据结构。
在本篇文章中,我们将通过实现一个链表类来深入了解 C++ 中链表的基本概念和使用方法。
### 链表的定义链表是一种线性数据结构,通常由一系列的结点(Node)组成,每个结点包含一个值和一个指向下一个结点的指针。链表可以用来存储一系列的元素,而这些元素之间没有固定顺序。
### 链表类的实现我们将通过实现一个 `List` 类来模拟链表的行为。
cpp// list.h#ifndef LIST_H#define LIST_Hclass Node {
public:
int value;
Node* next;
Node(int val) : value(val), next(nullptr) {}
};
class List {
private:
Node* head;
Node* tail;
int size;
public:
List() : head(nullptr), tail(nullptr), size(0) {}
~List();
void push_back(int val);
void push_front(int val);
int pop_back();
int pop_front();
int get_size() const { return size; }
bool is_empty() const { return size ==0; }
};
#endif // LIST_Hcpp// list.cpp#include "list.h"
#include <iostream>
List::~List() {
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
void List::push_back(int val) {
Node* newNode = new Node(val);
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
size++;
}
void List::push_front(int val) {
Node* newNode = new Node(val);
if (head) {
newNode->next = head;
head = newNode;
} else {
head = tail = newNode;
}
size++;
}
int List::pop_back() {
if (!tail) return -1; // list is empty int val = tail->value;
Node* temp = head;
while (temp->next != tail) {
temp = temp->next;
}
delete tail;
tail = temp;
size--;
return val;
}
int List::pop_front() {
if (!head) return -1; // list is empty int val = head->value;
Node* temp = head;
head = head->next;
if (head == nullptr) {
delete temp;
tail = nullptr;
} else {
delete temp;
}
size--;
return val;
}
### 使用示例
cppint main() {
List list;
// push_back list.push_back(1);
list.push_back(2);
list.push_back(3);
std::cout << "Size: " << list.get_size() << std::endl; // Output: Size:3 // pop_back int val = list.pop_back();
std::cout << "Popped value: " << val << std::endl; // Output: Popped value:3 std::cout << "Size: " << list.get_size() << std::endl; // Output: Size:2 // push_front list.push_front(4);
list.push_front(5);
std::cout << "Size: " << list.get_size() << std::endl; // Output: Size:4 return0;
}
### 总结在本篇文章中,我们通过实现一个链表类来深入了解 C++ 中链表的基本概念和使用方法。我们学习了链表的定义、链表类的实现以及链表的常用操作(如 push_back、push_front、pop_back 和 pop_front)。最后,我们通过一个示例程序演示了链表的使用方法。
希望本篇文章能够帮助你更好地理解 C++ 中链表的概念和使用方法。

