[英]Segmentation fault while implementing linkedlists in c++
我目前正在学习数据结构,我试图创建一个 function 插入以在第 n 个 position 插入一个节点,但我总是遇到分段错误,请您帮忙。
#include <iostream>
using namespace std;
struct node {
int data;
node* next;
};
struct node* head = NULL;
void insert(int dat, int pos) {
node* temp = new node;
temp->data = dat;
temp->next = NULL;
if (pos == 1) {
temp->next = head;
head = temp;
return;
}
node* newtemp = head;
for (int i = 0; i <= pos - 1; i++) {
newtemp = newtemp->next;
}
temp->next = newtemp->next;
newtemp->next = temp;
}
void print() {
node* temp = head;
while (temp != NULL) {
cout << temp->data;
temp = temp->next;
}
cout << endl;
}
int main() {
head = NULL;
insert(4, 1);
insert(6, 2);
print();
}
它应该是
i<pos-1
temp->next=newtemp->next;
newtemp->next=temp;
你应该检查链接列表是否有你给的 position
即,如果您通过将第 6 个 position 中的节点添加到具有 2 个节点的链表,它会给您分段错误。
按NULL->下一个
所以你应该检查链表的长度是否小于或等于position。
flag=false;
while(temp!=NULL)
{
if(i==Pos){
flag=true;
break;
}
temp=temp->next;
i++;
}
如果标志是假的,那么长度是不够的,否则你的东西在临时
看一下insert()
function这个语句:
for (int i = 0; i <= pos - 1; i++) {
对于插入元素6
,您将给出定位2
。
First iteration:
initialize i with 0
0 <= 2 - 1 ==> true
newtemp = newtemp->next
[After this statement, newtemp is NULL because your linked list has only one element]
i++ ==> i is now 1
Second iteration
1 <= 2 - 1 ===> true
newtemp = newtemp->next
[newtemp is NULL and this statment will attempt to access next of a NULL
which is resulting in segmentation fault]
我希望您了解分段错误的原因并且一个简单的更改可以解决这个问题 - 添加NULL
检查newtemp
节点,像这样
for (int i = 0; i < pos && newtemp->next != NULL; i++) {
您的代码不会检查传递的pos
值的有效性,并且在您当前的实现中,如果pos
值大于链表的大小,它将在列表末尾添加元素。 当pos
的值无效时,您可能想抛出错误。 此外,您不会释放分配给链表节点的 memory。 遵循良好的编程习惯 - 在程序退出之前释放分配的 memory。
额外的:
由于您在 c++ 中实现链表,因此您应该在实现中使用面向 object 的概念。 例如,捆绑数据和函数在一个单元中对该数据进行操作:
class Node {
private:
int data;
Node* next;
public:
// Add constructor for initialization of memeber variables
// Add destructor for cleanup and release memory
void insert(int dat, int pos);
void print();
};
更好的实现方式是将节点和链表分隔在两个不同的类中,并将它们的数据与各自的操作绑定。 例如
class Node {
private:
int data;
Node* next;
public:
Node();
Node(const int& val);
void setData(const int& val);
int getData() const;
void setNext(Node* const nodePtr);
Node* getNext() const;
};
单链表 class LinkedList
由Node
对象组成:
class LinkedList {
private:
Node* headNode;
Node* tailNode;
Node* currNode;
unsigned int count;
public:
LinkedList(); // constructor
// other overload of constructor, copy constructor, assignment operator, move semantics ....
~LinkedList(); // destructor
bool insertNode(const Node& newNode);
// other overload of insert, like insert at given position, at head of list, at tail of list etc..
unsigned int getCount() const;
Node* getHeadNode() const;
Node* getCurrNode() const;
Node* getTailNode() const;
bool deleteNode(const Node& node);
// other overload of delete node like detete tail node, delete head node etc.
bool deleteList();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.