Попытка разбить круговой связанный список. Отображение вывода, но сбой. ошибка во время выполнения в ideone

здесь я пытаюсь разбить круговой связанный список на две части. Когда я нажимаю Run, вывод идет правильно, но программа падает. Я не знаю причину, почему это происходит.
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();}

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 а затем следующая проверка в цикле fast_ptr->link сломается, потому что вы пытаетесь разыменовать нулевой указатель

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector