#include
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);
}
该回答引用GPTᴼᴾᴱᴺᴬᴵ
在程序中,链表创建和节点插入操作是正确的。但是,在最后输出链表时,程序中有一个无限循环的 while 循环,因此程序永远不会执行到 Print 函数。
为了解决这个问题,可以将 while 循环中的 return 0; 语句移动到 while 循环结束后,也就是 cmp 函数和 Print 函数之间,这样就可以正确输出链表了。另外,在 cmp 函数中,需要正确处理新节点的插入位置,应该在链表中找到合适的位置,然后将新节点插入到链表中。
下面是修改后的代码:
#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;
while (p->next != NULL && e >= p->next->data)
{
p = p->next;
}
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;
}
这个程序中,cmp 函数通过遍历链表找到合适的插入位置,然后将新节点插入到链表中。Print 函数则用于输出链表的每个节点的值。
cmp函数如果是插入,你咋没有循环比较判断呢?if就能决定插入位置?
至于不输出,是因为main函数中,当输入-1时,你return 0直接结束程序了啊,将return 0改为break跳出while循环就行了
该回答引用ChatGPT
在你的主函数中,你没有正确地调用Print函数。这是因为,你在while循环中无限等待用户的输入,但在退出循环时,你返回了0,这会导致程序直接退出而没有打印链表的内容。为了解决这个问题,你可以将Print函数调用移到while循环的外部,或者将while循环中的return语句替换为break语句,以允许程序继续执行Print函数。
另外,你的cmp函数似乎有一些逻辑错误。在当前实现中,它只能将新元素添加到链表的开头。如果你想将新元素插入到链表的正确位置,你需要在遍历链表时查找正确的插入位置。