面试题答案
一键面试设计思路
- 链表节点模板类:定义一个模板类
ListNode
,它包含一个数据成员和一个指向下一个节点的指针。数据成员的类型由模板参数决定,这样可以在编译期确定节点的数据类型。 - 链表模板类:定义一个模板类
TypeSafeList
,它包含链表的头节点指针和一些操作链表的成员函数,如插入节点、删除节点等。这些操作函数在编译期检查节点的数据类型,以确保类型安全。 - 类型检查:通过模板参数匹配,在编译期就保证只有相同数据类型的节点可以插入到链表中。
核心代码
// 链表节点模板类
template <typename T>
struct ListNode {
T data;
ListNode* next;
ListNode(const T& value) : data(value), next(nullptr) {}
};
// 链表模板类
template <typename T>
class TypeSafeList {
private:
ListNode<T>* head;
public:
TypeSafeList() : head(nullptr) {}
~TypeSafeList() {
while (head != nullptr) {
ListNode<T>* temp = head;
head = head->next;
delete temp;
}
}
// 插入节点到链表头部
void insert(const T& value) {
ListNode<T>* newNode = new ListNode<T>(value);
newNode->next = head;
head = newNode;
}
// 删除链表中值为指定值的节点
void remove(const T& value) {
ListNode<T>* current = head;
ListNode<T>* prev = nullptr;
while (current != nullptr && current->data != value) {
prev = current;
current = current->next;
}
if (current == nullptr) {
return;
}
if (prev == nullptr) {
head = current->next;
} else {
prev->next = current->next;
}
delete current;
}
};
可以这样使用这个链表:
int main() {
TypeSafeList<int> intList;
intList.insert(10);
intList.insert(20);
intList.remove(10);
// 下面这行代码会在编译期报错,因为类型不匹配
// TypeSafeList<int> intList2;
// intList2.insert("not an int");
return 0;
}