我正在为一个应该是双向链表的类编写程序。它可以编译,但是当我尝试执行命令 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;
}