[英]Merge two sorted link lists
我想通过指针操作合并两个排序的链接列表,但卡在了这一点上。 无法找出错误。 请帮帮我。 我认为问题出在 while 循环中。 我想让它节省空间,不想再列出一个清单。
#include<iostream>
#include<conio.h>
using namespace std;
struct s
{
int info;
s *next;
};
int main()
{
int i;
char choice = 'y';
s *ptr1, *ptr2, *start1, *start2, *reversedHead, *temp;
ptr1= new s;
start1=ptr1;
cout<<"SIZE OF A NODE IS "<<sizeof(s)<<" BYTES"<<endl<<endl;
while(choice=='y')
{
cout<<"Enter info for node: ";
cin>>i;
ptr1->info = i;
cout<<"Do you wish to enter more nodes.? 'y'/'n'"<<endl;
cin>>choice;
if(choice=='y')
{
ptr1->next = new s;
ptr1 = ptr1->next;
}
else
{
ptr1->next = NULL;
}
}
choice = 'y';
ptr2= new s;
start2=ptr2;
cout<<"SIZE OF A NODE IS "<<sizeof(s)<<" BYTES"<<endl<<endl;
while(choice=='y')
{
cout<<"Enter info for node: ";
cin>>i;
ptr2->info = i;
cout<<"Do you wish to enter more nodes.? 'y'/'n'"<<endl;
cin>>choice;
if(choice=='y')
{
ptr2->next = new s;
ptr2 = ptr2->next;
}
else
{
ptr2->next = NULL;
}
}
ptr1=start1;
ptr2=start2;
while(ptr1->next!=NULL || ptr2->next!=NULL)
{
if(ptr1->info < ptr2->info)
{
if(ptr1->next->info < ptr2->info)
ptr1=ptr1->next;
else
{
ptr2=temp;
ptr2=ptr2->next;
temp->next=ptr1->next;
ptr1->next=temp;
}
}
else
{
if(ptr2->next->info < ptr1->info)
ptr2=ptr2->next;
else
{
ptr1=temp;
ptr1=ptr1->next;
temp->next=ptr2->next;
ptr2->next=temp;
}
}
}
if(ptr1->next==NULL)
ptr1->next=ptr2;
else
ptr2->next=ptr1;
cout<<"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
if(start1->info>start2->info)
{
ptr2=start2;
while(ptr2!=NULL){
cout<<ptr2->info<<"\t";
ptr2=ptr2->next;}
}
else
{
ptr1=start1;
while(ptr1!=NULL){
cout<<ptr1->info<<"\t";
ptr1=ptr1->next;}
}
getch();
}
没有全部检查,但让我们从这里开始:
while(ptr1->next!=NULL || ptr2->next!=NULL)
它应该是&&
而不是||
因为您不想在其中一个列表中的下一个条目为空时继续比较(您确实在 while 循环中的一个 ifs 中使用了它的内容)
您的 while 循环条件不太正确。
while(ptr1->next!=NULL || ptr2->next!=NULL)
很好,但前提是两个列表的长度相同!。 当列表的长度不同时, ptr1->next
或ptr2->next
将为NULL
,您将收到分段错误。 更改为&&
不是正确的做法,因为您将丢失其中一个列表的末尾!
用这个:
while((ptr1 != NULL && ptr2 != NULL) && (ptr1->next!=NULL || ptr2->next!=NULL))
现在,在你的循环中,你有这样的测试:
if(ptr1->next->info < ptr2->info)
将其替换为
if(ptr1 != NULL && ptr1->next->info < ptr2->info)
这样不等长的列表就不会提前终止,也不会在内部出现段错误。
接下来,在插入操作中,您执行以下操作
ptr1=temp;
ptr1=ptr1->next
和
ptr2=temp;
ptr2=ptr2->next;
这很糟糕,因为temp
未定义,因为您从未向其中写入任何有效数据! 这里的错误是你的任务是错误的。 您应该分别完成temp=ptr1
和temp=ptr2
。
最后,修复等长输入列表的清理操作需要考虑到不等长输入列表可能导致ptr1
或ptr2
为NULL
的事实:
if(ptr1 != NULL && ptr1->next==NULL)
ptr1->next=ptr2;
else if (ptr2 != NULL)
ptr2->next=ptr1;
一切似乎都很好。 我已经在1 3 5
、 2 4 6
和1 3
、 2
和1 4
、 2 3
和1 3
、 2 3
上测试了结果代码,并且所有的工作都符合我的预期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.