我正在为一个应该是双向链表的类编写程序。它编译,但当我尝试执行命令addleft或addright时,我得到一个分段错误错误。我对C ++很新,所以任何建议都会很棒。我发布了代码的相关部分。
列表头文件:
//list.h
#include <string>
using namespace std;
class List {
friend class Node;
public:
List();
void addleft(int);
void addright(int);
int left();
int right();
void print();
bool search(int);
//Node *head;
//Node *tail;
//Node *n;
};
列出类文件:
#include <iostream>
#include <string>
#include <stdio.h>
#include "List.h"
#include "Node.h"
using namespace std;
Node *current;
Node *tail;
Node *head;
Node *n;
List::List() {
}
void List::addleft(int a) {
n = new Node; //The pointer n points to a new Node
n->number = a; //Set the value in the node
n->next = head; //Point the node to the old head of the linked list
head->prev = n; //Link the old head node to the new node
head = n; //Set the new node as the new head of the linked list
head->prev = NULL; //Make the new node's previous pointer point to nothing (NULL)
if(current == NULL) { //If the list is empty...
current = n; //Set the new node as the current node pointer
}
}
void List::addright(int a) {
n = new Node; //The pointer n points to a new Node
n->number = a; //Set the value in the node
n->prev = tail; //Point the node to the old head of the linked list
tail->next = n; //Link the old tail node to the new node
tail = n; //Set the new node as the new tail of the linked list
tail->next = NULL; //Make the new node's next pointer point to nothing (NULL)
if(current == NULL) { //If the list is empty...
current = n; //Set the new node as the current node pointer
}
}
int List::left() {
current = current->prev;
return current->number;
}
int List::right() {
current = current->next;
return current->number;
}
void List::print() {
}
bool List::search(int a) {
int search;
//while(search != tail) {
//}
}
节点头文件:
//node.h
using namespace std;
class Node {
friend class List;
public:
Node();
private:
int number;
Node *next;
Node *prev;
};
节点类文件:
#include <iostream>
#include <string>
#include <stdio.h>
#include "List.h"
#include "Node.h"
using namespace std;
Node::Node() {
next = NULL;
prev = NULL;
}
答案 0 :(得分:2)
我猜测head
和tail
最初初始化为空指针。这就是为什么第一次尝试添加任何崩溃的原因。如果是这种情况,您必须通过代码的特殊分支处理第一次添加。当head
和tail
都为空时,必须专门针对这种情况编写该特殊分支。
编辑:在看到更多代码后,我们可以得出结论,您的代码确实如此。
然而,编写List
类然后将head
和tail
声明为文件范围变量(而不是使它们成为List
类的成员)毫无意义。看起来你最初宣称它们是类成员,但后来评论了这些成员。为什么???