有效合并两个已排序的链接列表

时间:2012-11-12 21:46:43

标签: c++ algorithm merge linked-list

  

可能重复:
  Merge two sorted link lists

我想通过指针操作合并两个已排序的链接列表,并达到了这个目的。无法弄清楚这是否是最有效的方案(记忆方面和时间方面)。请帮帮我。我想提高效率,不想再制作另一份清单。

也许在两个链接列表中输入数据值的另一种方式.... :) 帮我。我想不出来。

#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;
                  }
}

if(start1->info<start2->info)
{
                             ptr1=start1;
                             ptr2=start2;
}
else
{
    ptr1=start2;
    ptr2=start1;
}
while(ptr1 != NULL && ptr2 != NULL)
{
           if(ptr1->next==NULL)
           {
                ptr1->next=ptr2;
                while(ptr2!=NULL)
                ptr2=ptr2->next;
           }
           else if(ptr1->next->info >= ptr2->info)
           {
                temp=ptr2;
                ptr2=ptr2->next;
                temp->next=ptr1->next;
                ptr1->next=temp;
           } 
           else if(ptr1->next->info < ptr2->info)
                ptr1=ptr1->next;                       
}
cout<<"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n \n";                    
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();
}

0 个答案:

没有答案