试图拆分循环链表。显示输出但崩溃。在ideone中显示运行时错误

时间:2016-06-09 12:27:54

标签: c++ linked-list circular-list

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

#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();



}

1 个答案:

答案 0 :(得分:0)

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中的下一个检查会崩溃,因为你试图取消引用空指针