NashZhou

广告算法工程师,目前致力于关键词广告的效果自动优化

Sequence.h

1 #include <cstdio>
2 #include <cstdlib>
3 //顺序表 Freeze 2010 10 6
4 #define ADDSIZE 5 //表分配存储空间分配增量
5 typedef int SElemType;
6
7 typedef struct {
8 SElemType *base; //存储空间基指针
9 int size; //长度,默认为0
10 int capacity; //容量
11 }Sequence;
12
13
14 void initSequence(Sequence &S,int capacity); //构造一个顺序表S,此处为引用
15 void freeSequence(Sequence &S); //销毁顺序表S,此处为引用
16 bool sequenceIsEmpty(const Sequence S); //若表S为空,则返回ture,否则返回false
17 void addCapacity(Sequence &S,int addsize); //增加表容量,此处为引用
18 void insert(Sequence &S,SElemType e,int i); //在第i个位置插入e,i从1到n
19 SElemType remove(Sequence &S,int i); //删除第i个元素,i从1到n
20
21 //构造一个空顺序表S
22 void initSequence(Sequence &S,int capacity=ADDSIZE)
23 {
24 freeSequence(S);
25 S.base=(SElemType *)malloc((capacity+1)*sizeof(SElemType));
26 if(!S.base)
27 {
28 printf("内存不足\n");
29 exit(1);
30 }
31 S.size=0;
32 S.capacity=capacity;
33 }
34
35 //销毁顺序表S
36 void freeSequence(Sequence &S)
37 {
38 if (S.capacity>0)
39 {
40 free(S.base);
41 }
42 }
43
44
45 //若顺序表S为空,则返回ture,否则返回false
46 bool sequenceIsEmpty(const Sequence S)
47 {
48 return(S.size==0);
49 }
50
51
52 //在顺序表的第i个位置插入e
53 void insert(Sequence &S,SElemType e,int i)
54 {
55 if(sequenceIsEmpty(S)||i<1||i>S.size)
56 {
57 printf("插入数据失败!\n");
58 exit(0);
59 }
60 if (S.size>=S.capacity) { //表满,追加存储空间
61 addCapacity(S,ADDSIZE);
62 }
63 for (int j=S.size-1;j>=i-1;j--)
64 {
65 S.base[j+1]=S.base[j];
66 }
67 S.base[j]=e;
68 S.size++;
69 }
70
71
72 //删除顺序表中第i个元素
73 SElemType remove(Sequence &S,int i)
74 {
75 if(sequenceIsEmpty(S)||i<1||i>S.size)
76 {
77 printf("插入数据失败!\n");
78 exit(0);
79 }
80 SElemType temp=S.base[i-1];
81 for (int j=i-1;j<S.size-2;j--)
82 {
83 S.base[j]=S.base[j+1];
84 }
85 S.size--;
86 return temp;
87 }
88 //增加栈容量
89 void addCapacity(Sequence &S,int addsize=ADDSIZE)
90 {
91 SElemType *temp=(SElemType *)realloc(S.base,(S.capacity+addsize+1)*sizeof(SElemType));
92 if(!temp)
93 {
94 printf("无法增加容量,内存不足\n");
95 exit(1);
96 }else{
97 if(S.base!=temp)
98 S.base=temp;
99 S.capacity+=addsize;
100 }
101 }

posted on 2011-05-16 17:44  NashZhou  阅读(170)  评论(0编辑  收藏  举报

导航