6. 设A=(a1,…,am)和B=(b1,…,bn)均为顺序表,A’和B’分别为A和B中除去最大共同前缀后的子表,若A’=B’=空表,则A=B;若A’=空表,而B’!=空表,或者两者都不为空表,且A’的首元小于B’的首元,则A<B;否则A >B. 试编程,求出A,B的大小。
# include <stdio.h>
# include <stdlib.h>
# define initsize 20
# define LISTINCREMENT 5
typedef int ElemType;
typedef struct
{
ElemType * elem;
int length;
int listsize;
} SqList;
void IntiList ( SqList & L, int n)
{
ElemType * p;
L. elem = ( ElemType * ) malloc ( initsize* sizeof ( ElemType) ) ;
if ( ! L. elem)
{
printf ( "分配失败" ) ;
}
printf ( "请依次输入顺序表的元素:\n" ) ;
for ( p = L. elem; p < L. elem+ n; p++ )
{
scanf ( "%d" , p) ;
}
L. length = n;
L. listsize = initsize;
}
void IntiList_NULL ( SqList & L)
{
L. elem = ( ElemType * ) malloc ( initsize* sizeof ( ElemType) ) ;
if ( ! L. elem)
{
printf ( "分配失败" ) ;
}
L. length = 0 ;
L. listsize = initsize;
}
void ListInsert ( SqList & L, int i, ElemType e)
{
ElemType * p, * q, * newbase;
q= L. elem+ i- 1 ;
if ( i< 1 || i> L. length+ 1 )
{
printf ( "插入元素位置不合法\n" ) ;
}
if ( L. length>= L. listsize)
{
newbase= ( ElemType * ) realloc ( L. elem, ( L. listsize+ LISTINCREMENT) * sizeof ( ElemType) ) ;
if ( ! newbase)
{
printf ( "分配失败" ) ;
}
L. elem= newbase;
L. listsize+ = LISTINCREMENT;
}
for ( p= L. elem+ L. length- 1 ; p>= q; p-- )
{
* ( p+ 1 ) = * p;
}
* q= e;
++ L. length;
}
void compare ( SqList A, SqList B, SqList & A1, SqList & B1)
{
int i;
ElemType * pa, * pb;
i= 1 ;
pa= A. elem;
pb= B. elem;
while ( * pa== * pb)
{
ListInsert ( A1, i, * pa) ;
ListInsert ( B1, i, * pb) ;
pa++ ;
pb++ ;
i++ ;
}
if ( A1. length!= 0 || B1. length!= 0 )
{
if ( * pa< * pb)
{
printf ( "A<B\n" ) ;
}
else
{
printf ( "A>B\n" ) ;
}
}
else
{
printf ( "A=B\n" ) ;
}
}
int main ( )
{
int n1, n2;
SqList A, B, A1, B1;
printf ( "请输入顺序表A的元素个数n1:\n" ) ;
scanf ( "%d" , & n1) ;
IntiList ( A, n1) ;
printf ( "请输入顺序表B的元素个数:\n" ) ;
scanf ( "%d" , & n2) ;
IntiList ( B, n2) ;
IntiList_NULL ( A1) ;
IntiList_NULL ( B1) ;
printf ( "\n" ) ;
compare ( A, B, A1, B1) ;
return 0 ;
}