线性表C语言实现

  1 #include <stdio.h>
  2 #include <malloc.h>
  3 #define bool int
  4 #define True 1
  5 #define False 0
  6 #define ERROR -1
  7 #define SIZE 100
  8 /*
  9     1、初始化线性表
 10     2、删除线性表
 11     3、判定是否为空表
 12     4、线性表长度
 13     5、输出线性表全部元素
 14     6、按元素位置查找
 15     7、按元素值查找
 16     8、插入
 17     9、删除
 18     10、在末尾添加值
 19     11、删除末位置
 20 */
 21 typedef struct {
 22     int data[SIZE];
 23     int length;
 24 } seq_list;
 25 
 26 // 初始化
 27 void init_list(seq_list* list)
 28 {
 29     // 分配存储线性表的空间
 30     list->data = (seq_list*)malloc(sizeof(seq_list));
 31     list->length = 0;
 32 }
 33 
 34 // 销毁线性表
 35 void destroy_list(seq_list* list)
 36 {
 37     free(list);
 38 }
 39 
 40 // 判断是否为空表
 41 bool list_empty(seq_list* list)
 42 {
 43     // 是空表返回 1, 不是0
 44     return (list->length == 0);
 45 }
 46 
 47 // 线性表长度
 48 int list_length(seq_list* list)
 49 {
 50     return (list->length);
 51 }
 52 
 53 // 输出线性表
 54 void disp_list(seq_list* list)
 55 {
 56     int i;
 57     for (i=0; i<length; i++){
 58         printf("%d", list->data[i]);
 59     }
 60     printf("
");
 61 }
 62 
 63 // key 位置元素
 64 int get_elem(seq_list* list, int key)
 65 {
 66     int value = ERROR;
 67     if (-1 < key && key < list->length){
 68         n = list->data[key];
 69     }
 70     return n;
 71 }
 72 
 73 // 按值查找, 返回位置
 74 int locate_elem(seq_list* list, int value)
 75 {
 76     int key = -1;
 77     int i;
 78     for (i=0; i<list->length; i++){
 79         if (list->data[i] == value){
 80             key = i;
 81             break;
 82         }
 83     }
 84     return key;
 85 }
 86 
 87 // 插入 value 到 key 位置
 88 bool list_insert(seq_list* list, int value, int key)
 89 {
 90     bool n = False;
 91     int i;
 92     // 表未满, 位置合法, 才可插入
 93     if ((list->length < SIZE) && (-1 < key && key < list->length)){
 94         for (i=list->length; i != key; i--){
 95             list->data[i+1] = list->data[i]
 96         }
 97         list->data[key] = value;
 98         n = True;
 99         list->length++;
100     }
101     
102     return n;
103 }
104 
105 // 删除 key 位置元素
106 bool list_delete(seq_list* list, int key){
107     int i;
108     bool n = False;
109     if (-1 < key && key < list->length){
110         for (i=key; i<list->length-1; i++){
111             list->data[i] = list->data[i+1];
112         }
113         list->length--;
114     }
115     
116     return n;
117 }
118 
119 // 追加元素
120 bool list_append(seq_list* list, int value)
121 {
122     bool n = Flase;
123     // 表未满, 就可以追加
124     if (list->length < SIZE){
125         list->data[list->length] = value;
126         list->length++;
127         n = True;
128     }
129     
130     return n;
131 }
132 
133 // 删除末尾元素
134 bool list_pop(seq_list* list)
135 {
136     bool n = Flase;
137     if (list->length != 0){
138         list->length--;
139     }
140 }
原文地址:https://www.cnblogs.com/tingshuo123/p/7077945.html