数据结构(1) - 顺序表示例代码
顺序表
顺序表是在计算机内存中以数组的形式保存的线性表,线性表的顺序存储是指用一组地址连续的存储单元依次存储线性表中的各个元素、使得线性表中在逻辑结构上相邻的数据元素存储在相邻的物理存储单元中,即通过数据元素物理存储的相邻关系来反映数据元素之间逻辑上的相邻关系,采用顺序存储结构的线性表通常称为顺序表。顺序表是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中。
示例代码
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define MAX_DATA_SIZE 10 5 6 typedef struct _SEQLIST { 7 int data[MAX_DATA_SIZE]; 8 int last_index; 9 } SEQLIST, *LPSEQLIST; 10 11 /** 12 * seqlist_isempty - Determine if the table is empty. 13 */ 14 int seqlist_isempty(LPSEQLIST lplist) 15 { 16 return (-1 == lplist->last_index); 17 } 18 19 /** 20 * seqlist_isfull - Determine if the table is full up. 21 */ 22 int seqlist_isfull(LPSEQLIST lplist) 23 { 24 return ((MAX_DATA_SIZE - 1) == lplist->last_index); 25 } 26 27 /** 28 * seqlist_insert - Add the specified data by index. 29 */ 30 int seqlist_insert(LPSEQLIST lplist, int index, int data) 31 { 32 int i; 33 34 if ((index < 0) || (index > MAX_DATA_SIZE - 1)) { 35 printf("invalid index!\n"); 36 return -1; 37 } 38 39 /* Move the data behind the index. */ 40 for (i = lplist->last_index; i >= index; i--) 41 lplist->data[i + 1] = lplist->data[i]; 42 43 /* Insert the data. */ 44 lplist->data[index] = data; 45 46 /* Update the last index. */ 47 lplist->last_index++; 48 49 return 0; 50 } 51 52 /** 53 * seqlist_del - Deletes the specified data by index. 54 */ 55 int seqlist_del(LPSEQLIST lplist, int index) 56 { 57 int i; 58 59 if ((index < 0) || (index > MAX_DATA_SIZE - 1)) { 60 printf("invalid index!\n"); 61 return -1; 62 } 63 64 /* Move the data behind the index forward. */ 65 for (i = index; i < lplist->last_index; i++) 66 lplist->data[i] = lplist->data[i + 1]; 67 68 /* Update the last index. */ 69 lplist->last_index--; 70 71 return 0; 72 } 73 74 /** 75 * seqlist_init - Initialize sequence list. 76 */ 77 int seqlist_init(LPSEQLIST *lpHead) 78 { 79 /* Allocate memory space. */ 80 *lpHead = (LPSEQLIST)malloc(sizeof(SEQLIST)); 81 if (NULL == *lpHead) { 82 perror("malloc"); 83 exit(1); 84 } 85 86 (*lpHead)->last_index = -1; 87 88 return 0; 89 } 90 91 /** 92 * seqlist_exit - clear sequence list. 93 */ 94 int seqlist_exit(LPSEQLIST lpHead) 95 { 96 int i = -1; 97 98 if (!seqlist_isempty(lpHead)) { 99 for (i = 0; i < lpHead->last_index; i++) 100 seqlist_del(lpHead, i); 101 } 102 103 free(lpHead); 104 lpHead = NULL; 105 106 return 0; 107 } 108 109 void test_show(LPSEQLIST lplist) 110 { 111 int i; 112 113 for (i = 0; i <= lplist->last_index; i++) 114 printf("%d ", lplist->data[i]); 115 116 printf("\n"); 117 } 118 119 int main(void) 120 { 121 int i = -1; 122 123 LPSEQLIST lphead; 124 125 seqlist_init(&lphead); 126 127 for (i = 0; i < MAX_DATA_SIZE; i++) 128 seqlist_insert(lphead, i, i + 1); 129 130 test_show(lphead); 131 132 seqlist_del(lphead, 3); 133 134 test_show(lphead); 135 136 seqlist_exit(lphead); 137 138 return 0; 139 }
完整代码可以参考github: [Link] [https://github.com/Phoebus-Ma/C-Helper/tree/main/Class-1/List.C].