我目前正在使用链接列表数据结构。该列表有一个指向头节点的指针和一个指向尾节点的指针。
节点类如下所示
template<class Type> class Node
{
private:
Type* storedVertex;
Node<Type>* next;
public:
Node()
{
storedVertex = NULL;
next = NULL;
}
Node(Type &vertex): next(NULL)
{
storedVertex = &vertex;
}
Type* get_Vertex()
{
return storedVertex;
}
Node<Type>* get_Next()
{
return this->next;
}
void set_Next(Node<Type>* _node)
{
this->next = _node;
}
};
LinkList类:
template<class Type> class LinkList
{
private:
int sz; //number of entries in linked list.
Node<Type> *head = NULL;
Node<Type> *tail = NULL;
public:
LinkList(): sz(0)
{
//O(1)
}
~LinkList()
{}
void del_All()
{
while (head != NULL)
{
Node<Type>* tmp = head;
head = head->next;
delete tmp;
}
sz = 0;
tail = NULL;
}
// /*
void push_Front(Type _vertex)
{
Node<Type>* _node = new Node<Type>(_vertex);
if(head == NULL)
{
head = _node;
tail = _node;
sz++;
}
else
{
_node->next = head;
head = _node;
sz++;
}
}
void add_node(Type _vertex)
{
Node<Type>* _node = new Node<Type>(_vertex);
//Adds node to the back of the linkList.
if (head == NULL)
{
//cout << "ptr" << ptr->getNext() << endl;
head = _node;
tail = _node;
sz++;
}
else
{
Node<Type>* ptr = head;
while(ptr->get_Next() != NULL)
{
ptr = ptr->get_Next();
}
ptr->set_Next(_node);
this->tail = _node;
sz++;
}
//LinkList::printList();
}
bool is_Empty()
{
if(head==0) cout << "Empty" << endl;
return head==0;
}
Node<Type>* get_Head()
{
cout << "DEBUG:: IN GET HEAD" << endl;
if(head == NULL) return NULL;
return head;
}
void set_Head(Node<Type> _Node)
{
push_Front(_Node);
}
Type get_Tail()
{
if(tail == NULL) return NULL;
return tail;
}
//Accessors
int size()
{
return sz;
}
bool search_for(string data)
{
cout << "DEBUG 3" << endl;
if(this->get_Head() == NULL)
{
cout << "DEBUG 3.5" << endl;
return false;
}
else
{
cout << "DEBUG 4" << endl;
Node<Type>* ptr = head;
if(ptr = NULL) return false;
cout << "DEBUG AGAIN" << endl;
cout << "search_for() while loop was ";
while(ptr != NULL)
{
if(ptr->get_Vertex()->get_Data() == data)
{
cout << "not skipped" << endl;
return true;
}
ptr = ptr->get_Next();
cout << "not ";
}
cout << "skipped.";
return false;
}
}
};
主:
#include <iostream>
#include <string>
#include "Vertex.h"
#include "HashTable.h"
using namespace std;
int main()
{
LinkList<string> list;
cout << "*****Insert*****" << endl;
cout << "Data(string) to insert: ";
string data;
cin >> data;
Vertex<string>* vertex = new Vertex<string>(data);
bool insert;
insert = list.add_node(vertex);
return 0;
}
我的文件正在编译。当我运行add_Node函数时,它会一直运行,直到遇到任何语句,如(head == NULL)。这是我得到seg错误的地方。我不明白这是因为我发起了头向NULL?
答案 0 :(得分:0)
我能看到的唯一错误是:
if(ptr = NULL) return false;