设X={x1,x2,...,xn}和Y={y1,y2,...ym}为两个单链表,试写出将X和Y归并为一个单链表的算法,使得:
Z={x1,y1,x2,y2,...,xn,yn,xm+1,...xn} (m<n)
#include<stdio.h>
typedef struct node
{char x;struct node* next;}s;
s* s_create(s* h)
{
s *p,*head;char ch;
head=(s*)malloc(sizeof(s));
head->next=NULL;
scanf("%c",&ch);
while(ch!='\0') {p=(s*)malloc(sizeof(s));
p->char=ch;p->next=head->next;
head->next=p;
scanf("%c",&ch);}
return head;
}
void s_union(s* head1,s* head2)
{s *p=head1->next,*q=head2->next,*r=head1;
while(p!=NULL&&q!=NULL) {r->next=p;q->next=p->next;p->next=q;r=r->next;
q=q->next;p=p->next;}
if(p!=NULL) {r->next=p;}
else {r->next=q;}
void printf_s(*head)
{s *p=head->next;
while(p) {printf("%c",p->ch;p=p->next;);}}
main()
{
s *head1,head2;
head1=s_create(head1);
head2=s_create(head2);
printf_s(head1);
printf_s(head2);
s_union(head1,head2);
printf_s(head1);
}高手帮忙看下,错在哪儿了呢?本人穷,分给少了,不好意思!
呵呵,看看结果是什么啊?
还有,为什么判断条件不能是ch!='\0'呢,字符'\0'不就是0吗?
不好意思,main函数出了点小问题,改正如下
int main()
{
s *head1,*head2;
int length1=0,length2=0;
head1=s_create(&length1);
head2=s_create(&length2);
printf_s(head1);
printf_s(head2);
if(length1>length2)
{
s_union(head1,head2);
printf_s(head1);
}
else
{
s_union(head2,head1);
printf_s(head2);
}
return 0;
}
字符'\0'不是'0',而是一个转义字符,一般用在字符串结尾标志字符串的结束,是无法从输入获得的,要以0结尾的话应该写成'0'