|
我要实现的功能是归并两个双向链表,代码如下:
#include <stdio.h>
#include <malloc.h>
struct Dnode{
int data;
struct Dnode *next;
struct Dnode *prior;
};
void createlist(struct Dnode *head)
{
int e;
struct Dnode *p,*q;
q=head;
printf("输入非零数据:\n");
scanf("%d",&e);
while(e){
p=(struct Dnode *)malloc(sizeof(struct Dnode));
p->data=e;
q->next=p; p->prior=q;
q=p;
scanf("%d",&e);
}
p->next=head;
head->prior=p;
}
void display(struct Dnode *head)
{
struct Dnode *p;
p=head->next;
while(p!=head){
printf("%d\t",p->data);
p=p->next;
}
printf("\n");
}
void freelist(struct Dnode *head )
{
struct Dnode *p,*temp;
p=head->next;
while( p!=head ) {
temp=p;
p=p->next;
free(temp);
}
free(head);
}
void merge(struct Dnode *head1,struct Dnode *head2)
{
struct Dnode *p1,*p2,*p3;
p1=head1->next;
p2=head2->next;
p3=head2;
while(p1!=head1&&p2!=head2){
if((p1->data)<=(p2->data)){
p3->next=p1;
p1->prior=p3;
p1=p1->next;
p3=p1;
}
else{
p3->next=p2;
p2->prior=p3;
p2=p2->next;
p3=p2;
}
}
while(p1!=head1){
p3->next=p1;
p1->prior=p3;
p1=p1->next;
p3=p1;
if(p3->next=head1){
p3->next=head2;
head2->prior=p3;
}
}
while(p2!=head2){
p3->next=p2;
p2->prior=p3;
p2=p2->next;
p3=p2;
}
free(head1);
}
void main()
{
struct Dnode *head1,*head2;
head1=(struct Dnode *)malloc(sizeof(struct Dnode));
head1->next=head1;
head1->prior=head1;
printf("输入数据<递增>\n");
createlist(head1);
printf("正向生成的链表1为:\n");
display(head1);
head2=(struct Dnode *)malloc(sizeof(struct Dnode));
head2->next=head2;
head2->prior=head2;
createlist(head2);
printf("输入数据<递增>\n");
printf("正向生成的链表2为:\n");
display(head2);
merge(head1,head2); //归并后的链表为head2
printf("\n归并后的链表为:\n");
display(head2);
printf("\n");
freelist(head2);
}
编译能够通过,运行时不正常,不知为何,请教高手。
谢谢!!! |
|