c++ - 双向链表三元组
问题描述
卡在 C++ 中。嗨,我试图在双向链表中找到三元组的连续总和,这是我的程序。但是在 IDE(VS 代码)上运行它时,我收到 Segmentation Core Dumped 错误。我正在尝试使用将遍历列表并给出此类三元组程序总数的指针:->
#include<iostream>
using namespace std;
class node
{
public:
int data;
node* next,*prev;
};
void insert(node** head_ref,int data)
{
node* new_node = new node();
new_node->data = data;
new_node->next = (*head_ref);
new_node->prev = NULL;
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
void display(node* head)
{
cout<<"\nTraversal in forward direction \n";
while (head != NULL)
{
cout<<" "<<head->data<<"<=>";
head = head->next;
}
}
void triplet(node* head,int j)
{
node* nx;
node* pr;
int count=0;
while(head->next!=NULL)
{
head=head->next;
nx = head->next;
pr = head->prev;
cout<<"Insside while";
if(nx->data+head->data+pr->data==j)
{
count++;
}
}
cout<<"\n"<<count;
}
int main()
{
node* head = NULL;
insert(&head,7);
insert(&head,6);
insert(&head,5);
insert(&head,4);
insert(&head,3);
insert(&head,2);
insert(&head,1);
display(head);
triplet(head,6);
cout<<"\n";
}
解决方案
检查此代码:
head=head->next;
nx = head->next;
pr = head->prev;
您head
在访问之前进行设置head->next
。因此,您最终会取消引用空指针。我的意思是,一开始head->next
不为空,但现在可能。
您还应该检查 prev,第一次可以为 null。
事实上,head = head->next
应该是你在每个循环中应该做的最后一件事,像这样:
void triplet(node* head,int j)
{
node* nx;
node* pr;
int count=0;
while(head->next!=NULL)
{
nx = head->next;
pr = head->prev;
cout<<"Insside while";
if(pr && nx->data+head->data+pr->data==j)
{
count++;
}
head=head->next;
}
cout<<"\n"<<count;
}
更新:您还应该检查head != NULL
. 我之前没有提到它,因为在您的程序中 head 始终不是 NULL (在调用函数之前初始化)。
推荐阅读
- sql - SQL - 在查询中选择内选择
- c# - 用 C# 编写 Xunit 测试用例
- html - 如何将图像放在页面上以使它们倾斜。[附上图片。]
- api - Zoho Books API - Google 表格
- java - 为不同角色提供资源访问的方法是什么?
- weka - 在 weka 中,simpleEducationalLearningSchemes 包不起作用
- python - 如何使用 python 和 pandas 编写带有阿拉伯字符的 csv 文件?
- java - 在NetBeans中打印Jtable数据之前如何在每页纸中添加行和列
- amazon-web-services - 来自在 ECS/EC2 上运行的容器化应用程序的 CloudWatch 多行日志消息
- python - 如果列中出现足够多的 id,则在数据框中使用 TRUE 创建列