我正在尝试在 C++ 中实现一个简单的链表插入。现在,我的代码在第一次尝试时看起来像,代码本身是不言自明的,但我添加了一些明显的注释,因为 stackoverflow 不允许我在不发表评论的情况下发布问题:
// Simple class and struct node
struct node {
int data;
struct node *next;
};
class list {
// Member functions
private:
// Defining struct object
node *root;
public:
bool insertNode(node *root); // Insertion function
void print_list();
};
bool list::insertNode(node *n){
root->next = n;
return true;
/*
node *temp = new node;
temp->data = data;
if(root == NULL){
root->next = new node;`enter code here`
root->next->data = data;
root->next->next = NULL;
cout << "Coming" << "\n";
return true;
} else {
temp->next = root;
root = temp;
return true;
} */
}
void list::print_list(){
node *p = root;
// . Iterating the list
p = p->next;
while(p != NULL){
cout << p->data << "\n";
p = p->next;
}
}
int main(){
class list l;
node *n = new node;
n->data = 5;
n->next = NULL;
if(!l.insertNode(n)){
cout << "Failed" << "\n";
return 1;
}
l.print_list();
return 1;
}
问题是,当我尝试如下修改我的程序时,不同之处在于,如果我有一个 int 作为参数,而不是将节点作为插入函数中的参数,那么它会给我分段错误。
================================================== ========================
#include <string>
using namespace std;
struct node {
int data;
struct node *next;
};
class list {
private:
node *root;
public:
bool insertNode(int data);
void print_list();
};
// Insertion function
bool list::insertNode(int data){
if(root == NULL){
root = new node;
root->data = data;
root->next = NULL;
return true;
} else {
node *temp = new node;
temp->data = data;
temp->next = root;
root = temp;
return true;
}
return false;
}
// Print function
void list::print_list(){
node *p = root;
p = p->next;
while(p != NULL){
cout << p->data << "\n";
p = p->next;
}
}
// Main driver code
int main(){
class list l;
if(!l.insertNode(5)){
cout << "Failed" << "\n";`enter code here`
return 1;
}
l.print_list();
return 1;
}
输出:./p
5
0
Segmentation fault: 11
这意味着在插入函数中我传递了一个整数而不是一个节点,那么为什么会出现分段错误?由于root
在列表类中定义从未分配过内存,并且在我的插入函数中,如果我检测到 root 为空,那么我只是root = new node;
做错了什么?另一方面,如果我在插入函数中插入一个节点而不是“int”,那么我会得到正确的输出吗?有什么区别?
要使列表正常工作,需要对其进行正确初始化。你有一个裸指针,但你没有构造函数。你也没有析构函数。
class list
{
private:
node *root;
public:
List() { root = NULL; }
~List() { clear(); }
void clear()
{
node *p = root, *q;
while (p)
{
q = p->next;
delete p;
p = q;
}
root = NULL;
}
bool insertNode(node* p)
{
if (!p)
return false;
p->next = root;
root = p;
return true;
}
bool insertNode(int data)
{
node* p = new node;
if (!p)
return false;
p->data = data;
return insertNode(p);
}
// ...
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句