数据结构与算法---向量使用

头文件

#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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值