【发布时间】:2012-10-31 23:14:04
【问题描述】:
我想通过指针操作合并两个已排序的链接列表,但在这一点上卡住了。无法找出错误。请帮帮我。我认为问题出在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();
}
【问题讨论】:
-
到底是什么问题?你试过调试吗?
-
如果您提供了您在应用程序中尝试过的输入、您获得的输出以及您期望的输出,这将会有所帮助。另外,您没有使用
std::list有什么特别的原因吗? -
如果你只是想让代码工作,使用
std::list然后使用方法std::list::merge();快速简单。如果您有其他原因(例如学习),您将有更具体的原因,而不仅仅是它不起作用。 -
INPUTS-> 第一个列表中的 3,5,第二个列表中的 4,6。 OUTPUT(expected)->3,4,5,6 但是执行突然结束了。
-
我没有使用 std::list::merge() 因为我必须学习合并和指针。
标签: c++ pointers merge linked-list