线性表操作集
顺序存储
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last;
};
List MakeEmpty()
{
List L;
L = (List)malloc(sizeof(struct LNode));
L->Last = -1;
return L;
}
#define ERROR -1
Position Find( List L, ElementType X )
{
Position i = 0;
while( i <= L->Last && L->Data[i]!= X )
i++;
if ( i > L->Last ) return ERROR;
else return i;
}
bool Insert( List L, ElementType X, Position P )
{
Position i;
if ( L->Last == MAXSIZE-1) {
printf("表满");
return false;
}
if ( P<0 || P>L->Last+1 ) {
printf("位置不合法");
return false;
}
for( i=L->Last; i>=P; i-- )
L->Data[i+1] = L->Data[i];
L->Data[P] = X;
L->Last++;
return true;
}
bool Delete( List L, Position P )
{
Position i;
if( P<0 || P>L->Last ) {
printf("位置%d不存在元素", P );
return false;
}
for( i=P+1; i<=L->Last; i++ )
L->Data[i-1] = L->Data[i];
L->Last--;
return true;
}
链表
向老师提问
typedef struct LNode *PtrToLNode;
struct LNode {
ElementType Data;
PtrToLNode Next;
};
typedef PtrToLNode Position;
typedef PtrToLNode List;
#define ERROR NULL
Position Find( List L, ElementType X )
{
Position p = L;
while ( p && p->Data!=X )
p = p->Next;
if ( p )
return p;
else
return ERROR;
}
bool Insert( List L, ElementType X, Position P )
{
Position tmp, pre;
for ( pre=L; pre&&pre->Next!=P; pre=pre->Next ) ;
if ( pre==NULL ) {
printf("插入位置参数错误\n");
return false;
}
else {
tmp = (Position)malloc(sizeof(struct LNode));
tmp->Data = X;
tmp->Next = P;
pre->Next = tmp;
return true;
}
}
bool Delete( List L, Position P )
{
Position pre;
for ( pre=L; pre&&pre->Next!=P; pre=pre->Next ) ;
if ( pre==NULL || P==NULL) {
printf("删除位置参数错误\n");
return false;
}
else {
pre->Next = P->Next;
free(P);
return true;
}
}