首页 > 解决方案 > 双向链表三元组

问题描述

卡在 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";
} 

标签: c++

解决方案


检查此代码:

   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 (在调用函数之前初始化)。


推荐阅读