头文件
#ifndef _Vector_H
#define _Vector_H
enum boolean {FALSE,TRUE};
typedef enum boolean Bool;
typedef int ElementType;
struct vector
{
ElememtType *elements;
int ArraySize;
int VectorLength;
};
typedef struct vector Vector;
void GetArray(Vector *);
void InitVector(Vector *,int sz);
ElementType GetNode(Vector *V,int i);
void FreeVector(Vector *);
int Find(Vector *,ElementType);
Bool Remove(Vector *,int i);
#endif
实现文件
#include"vector.h"
#include<stdio.h>
#include<stdlib.h>
void GetArray(Vector *V)
{
V->elements = (ElementType *)malloc (sizeof(ElementType ) * V->ArraySize);
if(V->elements == NULL)
printf("memory allocation error\n");
}
void InitVector(Vector *V,int sz)
{
if(sz < 0)
printf("invalid array size\n");
else
{
V->ArraySize=sz;
V->VectorLength = 0;
GetArray(V);
}
}
ElementType GetNode(Vector *V,int i)
{
return (i < 0 || i >= V->VectorLength) ? NULL : V->elements[i];
}
void FreeVector(Vector *V)
{
free(V->elements);
}
int Find(Vector *V,ElementType x)
{
int i;
for(i=0;i<V->VectorLength;i++)
if(V->elements[i] == x)
return i;
return -1;
}
Bool Insert(Vector *V,ElementType x,int i)
{
int j;
if(V->VectorLength == V->ArraySize)
{
printf("overflow\n");
return FALSE;
}
else if(i < 0 || i> V->VectorLength)
{
for(j=V->VectorLength-1;j>=i;j--)
V->elements[j+1] = V->elements[j];
V->elements[i] = x;
V->VectorLength++;
return TRUE;
}
}
Bool Remove(Vector *V,int i)
{
int j;
if(V->VectorLength == 0)
{
printf("Vector is empty\n");
return FLASE;
}
else if (i<0 || i > VectorLength -1)
{
printf("position error\n");
return FALSE;
}
else
for(j=i;j<V->VectorLength-1;j++)
V->elements[j] = V->elements[j+1];
V->VectorLength--;
return TRUE;
}
Vector *Union(Vector *Va,Vector *Vb)
{
int m,n,i,k,j;
ElementType x;
Vector *Vc = (Vector*)malloc(sizeof(Vector));
n = Va->VectorLength;
m = Va->VectorLength;
InitVector(Vc,m+n);
j=0;
for(i=0;i<n;i++)
{
x = GetNode(Va,i);
Insert(Vc,x,j);
j++;
}
for(i=0;i<m;i++)
{
x = GetNode(Vb,i);
k=Find(Va,x);
if(k==-1)
{
Insert(Vc,x,j);
j++;
}
}
return Vc;
}
Vector *Insertsection(Vector *Va,Vector *Vb)
{
int m,n,i,k,j;
ElementType x;
Vector *Vc = (Vector)malloc(sizeof(Vector));
n=Va->VectorLength;
m=Vb->VectorLength;
InitVector(Vc,(m>n)?n:m);
i=0;
j=0;
while(i<m)
{
x = GetNode(Vb,i);
k = Find(Va,x);
if(k != -1)
{
Insert(Vc,x,j);
j++;
}
i++;
}
return Vc;
}