我们如何显示链接列表
How do we display a linked list?
,所以我创建了以下代码,但是显示功能给了我问题。每次我尝试使用它时,它都会变成无限的循环。有人可以看看它,告诉我出了什么问题吗?
#include<iostream.h>
#include<conio.h>
struct node{
int info;
node *next;
}*ptr,*start,*temp;
node* create_new()
{
ptr=new node;
cout<<"nEnter the data: ";
cin>>ptr->info;
ptr->next=NULL;
return ptr;
}
void insert_at_beg()
{
ptr=create_new();
if(start==NULL)
{
start=ptr;
}
if(start!=NULL)
{
ptr->next=start;
start=ptr;
}
}
void display()
{
temp=start;
while(temp->next!=NULL)
{
cout<<"t"<<temp->info;
temp=temp->next;
}
}
void insert_at_end()
{
if(start==NULL)
{
start=ptr;
}
if(start!=NULL)
{
ptr=create_new();
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
}
void delete_from_end()
{
if(start==NULL)
{
cout<<"NULL LL";
}
else
{
temp=start;
while(temp->next!=NULL)
{
ptr=temp;
temp=temp->next;
}
ptr->next=NULL;
delete temp;
}
}
void delete_from_beg()
{
if(start==NULL)
cout<<"nNULL LL";
else
start=start->next;
}
void delete_from_mid()
{
int el;
if(start==NULL)
{
cout<<"nNULL LL";
}
else
{
cout<<"nEnter element that you want to delete: ";
cin>>el;
temp=start;
while(temp->next!=NULL&&temp->info!=el)
{
ptr=temp;
temp=temp->next;
}
ptr->next=temp->next;
delete temp;
}
}
void main()
{
clrscr();
start=NULL;
temp=NULL;
ptr=NULL;
insert_at_beg();
display();
getch();
}
您的错误在此代码中:
void insert_at_beg()
{
ptr=create_new();
if(start==NULL)
{
start=ptr;
}
if(start!=NULL)
{
ptr->next=start;
start=ptr;
}
}
start
中的第一次将是无效的,因此您将进行start=ptr
。但是,现在if(start!=NULL)
是正确的,因此您将进行ptr->next=start
。由于ptr
和start
都指向相同的东西,您会创建一个无限的循环。
首先,我不建议您使用全局变量,尤其是当您拥有同一类型(和值)的函数时。
我的问题在于函数insert_at_beg():
// yes start is NULL initially
if(start==NULL)
{
start=ptr; // now start is not NULL!!
}
//This statement will also be entered.
if(start!=NULL)
{
ptr->next=start;
start=ptr;
}
}
而是使用else
if(start==NULL)
{
start=ptr; // now start is not NULL!!
}
else
{
ptr->next=start;
start=ptr;
}
}
另外,而不是:
#include<iostream.h>
#include<conio.h>
仅使用#include<iostream>
导致无限循环在其他地方的错误(insert_at_beg(),我在代码中看到有人已经添加了详细信息,所以我也不会这样做)。
您的代码仍然有问题:
void display()
{
temp=start;
while(temp->next!=NULL)
{
cout<<"t"<<temp->info;
temp=temp->next;
}
}
您不会打印最后的Enlemt。当当前元素的下一个(临时)为空时,您会停止。将其更改为
while(temp) // equivalent to while(temp !=NULL)
您的display
功能可以简化:
void display()
{
node * p = start;
while (p != NULL)
{
cout << "t" << p->info;
p = p->next;
}
cout << endl; // The side effect of this is to print blank line when empty list.
}
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表