1 /*******************************************************************
2 * > File Name: seqTable.c
3 * > Author: fly
4 * > Mail: XXXXXXXX@icode.com
5 * > Create Time: 2018年06月20日 星期三 09时45分29秒
6 ******************************************************************/
7
8 #include <stdio.h>
9 #include <stdlib.h>
10
11 #define Size 4
12
13 typedef struct Table
14 {
15 int *head;//声明一个名为head的长度不确定的数组,也叫“动态数组”
16 int length;//记录当前顺序表的长度
17 int size;//记录顺序表分配的存储容量
18 } table;
19
20 table initTable()
21 {
22 table t;
23 t.head = (int*)malloc(Size*sizeof(int));
24 if(!t.head)
25 {
26 perror("malloc error");
27 exit(0);
28 }
29 t.length = 0;//空表的长度初始化为0
30 t.size = Size;//空表的初始存储空间为Size
31 return t;
32 }
33
34 //查找函数,其中,elem表示要查找的数据元素的值
35 int selectTable(table t, int elem)
36 {
37 for(int i=0; i<=t.length; i++)
38 {
39 if(t.head[i]==elem)
40 {
41 return i+1;
42 }
43 }
44
45 return -1;//查找失败,返回-1
46 }
47
48 //更改函数,其中,elem为要更改的元素,newElem为新的数据元素
49 table amendTable(table t, int elem, int newElem)
50 {
51 int add = selectTable(t,elem);
52 t.head[add-1]=newElem;//由于返回的是元素在顺序表中位置,所以-1是该元素在数组中的下标
53 return t;
54 }
55
56 //插入函数,其中,elem为插入的元素,add为插入到顺序表的位置
57 table addTable(table t,int elem,int add)
58 {
59 //判断插入本身是否存在问题(如果插入元素位置比整张表的长度+1还大(如果相等,是尾随的情况))
60 //或者插入的位置本身不存在,程序作为提示并自动退出
61 if(add>t.length+1 || add < 1)
62 {
63 perror("Position error ");
64 return t;
65 }
66
67 //做插入操作时,首先需要看顺序表是否有多余的存储空间提供给插入的元素,如果没有,需要申请
68 if(t.length == t.size)
69 {
70 t.head=(int*)realloc(t.head,(t.size+1)*sizeof(int));
71 if(!t.head)
72 {
73 perror("realloc error");
74 return t;
75 }
76
77 t.size+=1;
78 }
79
80 //插入操作,需要将从插入位置开始的后续元素,逐个后移
81 for(int i=t.length-1; i>=add-1; i--)
82 {
83 t.head[i+1]=t.head[i];
84 }
85
86 //后移完成,直接将所需插入元素,添加到顺序表的相应位置
87 t.head[add-1] = elem;
88 //由于添加了元素,所以长度+1
89 t.length++;
90 return t;
91 }
92
93 table delTable(table t,int add)
94 {
95 if(add > t.length || add < 1)
96 {
97 perror("del position error");
98 exit(0);
99 }
100
101 for(int i=add; i<t.length; i++)
102 {
103 t.head[i-1] = t.head[i];
104 }
105 t.length--;
106 return t;
107 }
108
109 void displayTable(table t)
110 {
111 for(int i=0; i<=t.length-1; i++)
112 {
113 printf("%d\t",t.head[i]);
114 }
115 printf("\n");
116 }
117
118 int main(void)
119 {
120 table t1=initTable();
121 for(int i=1; i<=Size; i++)
122 {
123 t1.head[i-1]=i;
124 t1.length++;
125 }
126
127 printf("Original seq table :\n");
128 displayTable(t1);
129
130 for(int i=1; i<=5; i++)
131 {
132 printf("Insert elem 5 in 2nd position :\n");
133 t1=addTable(t1,5,2);
134 displayTable(t1);
135 }
136
137 printf("Del elem 1 :\n");
138 t1=delTable(t1,1);
139 displayTable(t1);
140
141 printf("Insert elem 5 in 2nd position :\n");
142 t1=addTable(t1,5,2);
143 displayTable(t1);
144
145 printf("Find the position of the elem 3 :\n");
146 int add = selectTable(t1,3);
147 printf("%d\n",add);
148
149 printf("Replace the elem 3 by 6 :\n");
150 t1=amendTable(t1, 3, 6);
151 displayTable(t1);
152
153 return 0;
154 }