尝试拆分循环链表.显示输出但崩溃.在 IDEone 中显示运行时错误

Trying to split circular linked list. Showing output but crashing. runtime error displaying in ideone

本文关键字:显示 IDEone 运行时错误 崩溃 输出 拆分 循环链表      更新时间:2023-10-16

在这里,我试图将循环链表分成两部分。当我按运行时,输出正确,但程序崩溃。我不知道为什么会发生这种情况。append() - 添加元素display()- 显示内容拆分 () - 将列表拆分为两部分。我的问题在这里

#include<iostream>
using namespace std;
class circll{
    private:
        struct node {
            int data;
            node *link;
        } *front, *rear, *head1, *head2 ; /*head1 and head2 declared to point to the respective heads after split*/
    public:
        circll()
        {front = rear = NULL;
        }
        void append(int );
        void display()
        {
                display1(head1);
                display1(head2);
        }
        void display1(node*);
        void split(); // my main problem is in this function
        ~circll()
        {
            node *q;
            while(front != rear)
            {
                q = front->link;
                delete front;
                front = q;
            }
            delete rear;
        }
};
void circll::append (int num) {

    if(front==NULL)
    {
        front=new node{num};
        rear=front;
        rear->link=front;
    }
    else{
        rear->link=new node{num};
        rear=rear->link;
        rear->link=front;
    }   
}

void circll::split(){
    if(front==NULL)
    {return;
    }
    node *slow_ptr = front;
    node *fast_ptr = front;
    while( fast_ptr->link != front && fast_ptr->link->link != front )
    {
        fast_ptr=fast_ptr->link->link;
        slow_ptr=slow_ptr->link;
    }
    if(fast_ptr->link->link == front)
    {
        fast_ptr = fast_ptr->link;
    }
    head1=front;
    if(front->link != front)
    {
        head2 = slow_ptr->link ;
    }
    fast_ptr->link = slow_ptr->link;
    slow_ptr->link = front;
    cout<<"split completed"<<endl;
}
void circll::display1(node * head){
    node *q=head;
    node *p=NULL;
    while(q!=p)
    {
        cout<<q->data<<" ";
        q=q->link;
        p=head;
    }
    cout<<endl;
}
int main()
{
    circll cl1;
    cl1.append(5);
    cl1.append(7);
    cl1.append(54);
    cl1.append(89);
    cl1.append(34);
    cl1.append(23);
    cl1.split();
    cl1.display();

}
while( fast_ptr->link != front && fast_ptr->link->link != front )
{
    fast_ptr=fast_ptr->link->link;
    slow_ptr=slow_ptr->link;
}
if(fast_ptr->link->link == front)
{
    fast_ptr = fast_ptr->link;

您不检查是否fast_ptr=fast_ptr->link->link == NULL.它可以是NULL的,然后在 while 循环中的下一次检查fast_ptr->link将粉碎,因为您正在尝试取消引用空指针