【发布时间】:2021-03-21 03:32:16
【问题描述】:
在 find(T item) 函数中,我正在检查输入的数据是否为字符串,然后我单独处理它,对于其他数据类型,我在其他情况下处理它,因为我使用字符串函数 compare()检查比赛。当链表中有匹配的字符串并返回节点并打印节点数据时,程序运行良好,但是当找不到匹配的字符串时,程序不会返回空的 tmp 节点,而是崩溃并说“分段错误(核心转储)”。有什么办法可以解决吗?
#include <iostream>
#include <typeinfo>
using namespace std;
template <typename T>
class Node {
public:
T data;
Node *next;
Node *prev;
Node(){};
};
template <typename T>
class LinkedList {
private:
Node<T> *head;
Node<T> *tail;
public:
LinkedList(){
head = NULL;
tail = NULL;
}
void insertHead(T item){
Node<T> *tmp = new Node<T>();
if (head == NULL){
head = tmp;
head->prev = NULL;
head->data = item;
head->next = NULL;
tail = tmp;
} else {
tmp->next = head;
tmp->data = item;
tmp->prev = NULL;
head->prev = tmp;
head = tmp;
}
}
void insertLast(T item){
Node<T> *tmp = new Node<T>();
tmp->data = item;
if (head == NULL){
head = tmp;
head->prev = NULL;
head->next = NULL;
tail = tmp;
} else {
tmp->prev = tail;
tail->next = tmp;
tmp->next = NULL;
tail = tmp;
}
}
Node<T>* find(T item){
Node<T> *tmp = head;
if (typeid(item) == typeid(string)){
string s, d;
s = item;
d = tmp->data;
while(tmp != NULL){
if(s.compare(d) == 0){
return tmp;
}
tmp = tmp->next;
d = tmp->data;
}
Node<string> *tmp = new Node<string>();
tmp->data = "";
return tmp;
} else {
while(tmp != NULL){
if(tmp->data == item){
return tmp;
}
tmp = tmp->next;
}
tmp = new Node<T>();
tmp->data = -1;
return tmp;
}
}
void print(){
Node<T> *tmp;
tmp = head;
while (tmp != NULL){
cout << tmp->data << "->";
tmp = tmp->next;
}
cout << endl;
}
};
int main(){
LinkedList<string> l;
l.insertHead("Abc");
l.insertHead("def");
l.insertHead("ghi jk");
Node<string>* tmp = new Node<string>();
tmp = l.find("ghi");
cout << tmp << endl;
l.print();
}
【问题讨论】:
标签: c++ class templates linked-list function-definition