#include
#include
struct list{
int num;
struct list *next;
};
typedef struct list aa;
aa *create( void );
aa *hebing( aa *s1, aa *s2 );
void clear( aa *cc );
int main( void )
{
aa *head1, *head2, *head3, *i;
head1 = create();
head2 = create();
head3 = hebing( head1, head2 );
for( i = head3; i != NULL; i = i->next ){
printf( "%d\t", i->num );
}
clear( head3 ); //只释放一次就可以了。它已经包括了head1和head2的内存空间,
//若是再继续释放已经释放的内存空间,将会产生错误
//clear( head2 );
//clear( head1 );
return 0;
}
aa *create()//创建
{
int no;
aa *head, *tail, *p;
head = tail = NULL;
scanf( "%d", &no );
while( no != -1 ){
//p = (aa *)malloc( sizeof( int ) ); 不对
p = (aa *)malloc( sizeof( aa ) );
p->num = no;
if( head == NULL ){
head = p;
}
else{
tail->next = p;
}
tail = p;
scanf( "%d", &no );
}
tail->next = NULL;
return head;
}
aa *hebing( aa *s1, aa *s2 )//合并
{
aa *head, *tail;
head = tail = NULL;
while( s1 != NULL && s2 != NULL ){
if( s1->num <= s2->num){
if( head == NULL ){
head = s1;
}
else{
tail->next = s1;
}
tail = s1;
s1=s1->next;
}
else
{
if(head==NULL)
{
head=s2;
}
else
{
tail->next=s2;
}
tail=s2;
s2=s2->next;
}
}
tail->next=s1?s1:s2;
return head;
}
void clear(aa *cc)
{
aa *tiny;
// tiny=cc;
/* while(cc->next!=NULL)
{
while(tiny->next!=NULL)
{
tiny=tiny->next;
}
free(tiny);
}*/
while( cc != NULL ){
tiny =cc;
cc = cc->next;
free( tiny );
}
}
温馨提示:答案为网友推荐,仅供参考