-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vector.c
110 lines (85 loc) · 1.64 KB
/
Vector.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <stdlib.h>
#include "Vector.h"
Vector *vtCreate()
{
Vector *pVt=calloc(1,sizeof(Vector));
return pVt;
}
void vtDestory(Vector *pVt)
{
free(pVt);
}
void vtAddBack(Vector *pVt,void *pNode)
{
if(pVt->nCount<pVt->nMemorySize)
{
pVt->pArray[pVt->nCount]=pNode;
pVt->nCount++;
return;
}
else
{
void **pMem;
if(pVt->nMemorySize)
pMem=malloc(sizeof(void *)*pVt->nMemorySize*2);
else
{
pMem=malloc(sizeof(void *)*VECTOR_BASE_SIZE);
pVt->nMemorySize=VECTOR_BASE_SIZE/2;
}
if(!pMem)
{
printf("Memory out of!\n");
return;
}
for(int i=0;i<pVt->nCount;i++)
pMem[i]=pVt->pArray[i];
free(pVt->pArray);
pVt->pArray=pMem;
pVt->pArray[pVt->nCount]=pNode;
pVt->nCount++;
pVt->nMemorySize<<=1;
}
}
void *vtRemove(Vector *pVt,int index)
{
void *pDel=vtGet(pVt,index);
if(!pDel) return NULL;
for(int i=index;i<pVt->nCount;i++)
{
pVt->pArray[i]=pVt->pArray[i+1];
}
pVt->nCount--;
if(pVt->nCount<pVt->nMemorySize/2 &&
pVt->nCount>=VECTOR_BASE_SIZE*2)
{
void **pMem;
if(pVt->nMemorySize)
pMem=malloc(sizeof(void *)*pVt->nMemorySize*2);
else
{
pMem=malloc(sizeof(void *)*VECTOR_BASE_SIZE);
pVt->nMemorySize=VECTOR_BASE_SIZE/2;
}
if(!pMem)
{
printf("Memory out of!\n");
return NULL;
}
for(int i=0;i<pVt->nCount;i++)
pMem[i]=pVt->pArray[i];
free(pVt->pArray);
pVt->pArray=pMem;
pVt->nMemorySize<<=1;
}
return pDel;
}
void *vtGet(Vector *pVt,int index)
{
if(index<0 || index>=pVt->nCount) return NULL;
return pVt->pArray[index];
}
int vtCount(Vector *pVt)
{
return pVt->nCount;
}