(链式存储)比较两个字符串A和B大小,若A>B,返回1,若A<B,返回-1,否则返回0。
#include
#include
#define MAXSIZE 100
typedef char datatype;
typedef struct linklist
{
datatype data;
struct linklist *next;
} node;
node *init()
{
node *head;
head=(node*)malloc(sizeof(node));
head->next=NULL;
return head;
}
void input(node *head,int sign)
{
node *p,*tail;
tail=head;
char a[MAXSIZE];
int i=0;
switch(sign)
{
case 100:
printf("请输入A:");
break;
case 101:
printf("请输入B:");
break;
}
gets(a);
while(a[i]!='\0')
{
p=(node*)malloc(sizeof(node));
p->data=a[i];
i++;
tail->next=p;
tail=p;
}
tail->next=NULL;
}
void print(node *headA,node *headB,int sign)
{
node *pA,*pB;
switch(sign)
{
case 101:
/*打印A*/
pA=headA->next;
if(pA==NULL)printf("\nA是空的!");
else
{
while(pA!=NULL)
{
printf("%c",pA->data);
pA=pA->next;
}
printf("\n");
}
/*打印B*/
pB=headB->next;
if(pB==NULL)printf("\nB是空的!");
else
{
while(pB!=NULL)
{
printf("%c",pB->data);
pB=pB->next;
}
printf("\n");
}
break;
default:
printf("比较结果为:%d\n",sign);
break;
}
}
int compare(node *headA,node *headB)
{
node *pA,*pB;
for(pA=headA->next,pB=headB->next; pA!=NULL&&pB!=NULL; pA=pA->next,pB=pB->next)
{
if(pA->data>pB->data)return 1;
if(pA->data
data)return -1;
}
if(pA==NULL&&pB!=NULL)return -1;
if(pB==NULL&&pA!=NULL)return 1;
if(pA==NULL&&pB==NULL)return 0;
return 0;
}
int main()
{
node *headA,*headB;
int sign=100;
headA=init();
headB=init();
input(headA,sign);
sign=101;
input(headB,sign);
print(headA,headB,sign);
sign=compare(headA,headB);
print(headA,headB,sign);
return 0;
}