就是说两个单链表,合并之后排序,其中单链表的长度不一,内为单词,合并之后怎样实现按首字母排序
有如下程序,本鸟只做到这.不知道怎么改了,望高手指教.谢谢.
只实现了数字排序.....
#include <stdio.h>
#include <malloc.h>
struct LNode
{ int data;
struct LNode *next;
};
struct LNode *insert(struct LNode *head,int x,int i);
void display(struct LNode *head);
struct LNode *combine(struct LNode *head1,struct LNode *head2);
main()
{
struct LNode *head1,*head2,*head3;
head1 = NULL;
head1 = insert(head1,2,1);
head1 = insert(head1,12,2);
head1 = insert(head1,67,3);
printf("123123123123\n");
display(head1);
printf("\n");
head2 = NULL;
head2 = insert(head2,8,1);
head2 = insert(head2,20,2);
head2 = insert(head2,33,3);
head2 = insert(head2,35,4);
printf("123123123123\n");
display(head2);
printf("\n");
head3 = combine(head1,head2);
printf("123123123123\n");
display(head3);
getchar();
}
struct LNode *insert(struct LNode *head,int x,int i)
{
int j=1;
struct LNode *s,*q;
q=head;
s=(struct LNode *) malloc ( sizeof(struct LNode) );
s->data=x;
if(i==1)
{
s->next=q;
head=s;
}
else
{
while(q->next != NULL)
{
q=q->next;
j++;
}
if(j==i-1)
{
s->next=q->next;
q->next=s;
}
else
printf("error! there is no position\n");
}
return(head);
}
void display(struct LNode *head)
{
struct LNode *q;
q=head;
if(q==NULL)
printf("this is a NULL\n");
else
if(q->next==NULL)
printf("%d",q->data);
else
{
while(q->next!=NULL)
{
printf("%d->",q->data);
q=q->next;
}
printf("%d",q->data);
}
}
struct LNode *combine(struct LNode *head1,struct LNode *head2)
{
int n;
struct LNode *p1,*p2,*p3,*head3;
head3=NULL;
p1=head1;
p2=head2;
p3=head3;
if(p1 == NULL && p2 == NULL)
printf("null!!!\n");
else
if(p1 != NULL && p2 == NULL)
return(head1);
else
if(p2 != NULL && p1 == NULL)
return(head2);
else
{ n=1;
while(p1 != NULL && p2 != NULL)
{
if(p1->data < p2->data)
{
head3=insert(head3,p1->data,n++);
p1=p1->next;
}
else
if(p1->data > p2->data)
{
head3=insert(head3,p2->data,n++);
p2=p2->next;
}
else
{
head3=insert(head3,p1->data,n++);
p1=p1->next;
p2=p2->next;
}
}
while(p1 != NULL && p2 == NULL)
{
head3=insert(head3,p1->data,n++);
p1=p1->next;
}
while(p2 != NULL && p1 == NULL)
{
head3=insert(head3,p2->data,n++);
p2=p1->next;
}
}
return(head3);
}