#include <iostream>
using namespace std;
typedef struct Lnode
{
int data;
struct Lnode *next;
}Lnode, *Linklist;
int creat ( Linklist &L )
{
L = new Lnode;
L->next = NULL;
Linklist p, q = L;
while (1)
{
p = new Lnode;
cin >> p->data;
if ( p->data == -1 )
{
return 0;
}
p->next = NULL;
q->next = p;
q = p;
}
}
void cmp ( Linklist &L, int e )
{
Linklist p, q;
p = L;
if ( e >= p->next->data )
{
q = new Lnode;
q->data = e;
q->next =
p->next = q;
p = q;
}
}
void Print (Linklist L)
{
Linklist p = L->next;
while ( p != NULL )
{
cout << p->data;
if ( p->next != NULL)
{
cout << " ";
}
p = p->next;
}
}
int main ()
{
int t;
Linklist L;
creat (L);
while ( 1 )
{
cin >> t;
if ( t == -1 )
{
return 0;
}
else
{
cmp (L, t);
}
}
Print (L);
}
为什么输出链表为空啊,调试了一下,好像是插入那里有问题
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
4条回答 默认 最新
- CodeBytes 2023-03-10 08:47关注
该回答引用ChatGPT
在函数 cmp 中,当链表 L 为空或 e 值小于 L 中第一个节点的值时,没有插入新的节点,导致最终输出的链表仍然是原始的输入链表。因此,需要增加一个判断链表 L 是否为空的条件,以及在需要插入新节点时,要修改新节点的 next 指针和前一个节点的 next 指针。同时,在 main 函数中需要将 Print(L) 函数调用语句放在 while 循环外面,否则在第一次输入 -1 后就会直接返回,无法输出链表。
以下是修正后的代码:
#include <iostream> using namespace std; typedef struct Lnode { int data; struct Lnode *next; } Lnode, *Linklist; int creat(Linklist &L) { L = new Lnode; L->next = NULL; Linklist p, q = L; while (1) { p = new Lnode; cin >> p->data; if (p->data == -1) { return 0; } p->next = NULL; q->next = p; q = p; } } void cmp(Linklist &L, int e) { Linklist p = L; if (p->next == NULL || e < p->next->data) { Linklist q = new Lnode; q->data = e; q->next = p->next; p->next = q; } else { while (p->next != NULL && e >= p->next->data) { p = p->next; } Linklist q = new Lnode; q->data = e; q->next = p->next; p->next = q; } } void Print(Linklist L) { Linklist p = L->next; while (p != NULL) { cout << p->data; if (p->next != NULL) { cout << " "; } p = p->next; } } int main() { int t; Linklist L; creat(L); while (1) { cin >> t; if (t == -1) { break; } cmp(L, t); } Print(L); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
- ¥60 pb数据库修改与连接
- ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
- ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
- ¥20 神经网络Sequential name=sequential, built=False
- ¥16 Qphython 用xlrd读取excel报错
- ¥15 单片机学习顺序问题!!
- ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
- ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
- ¥15 相敏解调 matlab