尝试拆分循环链表.显示输出但崩溃.在 IDEone 中显示运行时错误
Trying to split circular linked list. Showing output but crashing. runtime error displaying in ideone
在这里,我试图将循环链表分成两部分。当我按运行时,输出正确,但程序崩溃。我不知道为什么会发生这种情况。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
将粉碎,因为您正在尝试取消引用空指针
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 程序崩溃并显示"std::out_of_range"错误
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 显示错误输出的简单数组排序程序
- Qt自定义QPush按钮未显示在布局上
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 显示基于用户输入的整数的字符
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 尝试拆分循环链表.显示输出但崩溃.在 IDEone 中显示运行时错误
- 下面显示的代码片段在 Coliru 和 Ideone 中编译,但根据 iso § 8.5 p6,它不应该,还是我错过了什么?