顺序表C语言版

  1 #include <stdio.h>
  2 /*
  3  * 顺序表最多输入N个数
  4  */
  5 #define N 10
  6 #define OK 1
  7 #define ERROR -1
  8 
  9 
 10 struct sequeuelist {
 11     int *elem;
 12     int length;
 13     int listsize;
 14 };
 15 /*
 16  * 因为l是指针,所以请注意->的使用,而不是L.
 17  */
 18 int sequeuelist_init(struct sequeuelist *l) {
 19     l->elem = (int *)malloc(N * sizeof(int));
 20     if (!l->elem) {
 21         return ERROR;
 22     }
 23     l->length = 0;/* 空表长度为0 */
 24     l->listsize = N;/* 初始存储容量 */
 25     return OK;
 26 }
 27 /*
 28  * 插入函数,在实验时,可暂不考虑空间不足的情况
 29  */
 30 int sequeuelist_insert(struct sequeuelist *l, int i, int e) {
 31     int *q = NULL;
 32     int *p = NULL;
 33     q = &(l->elem[i-1]);
 34     for (p = &(l->elem[l->length]); p > q; --p) {
 35         *(p+1) = *p;
 36     }
 37     *q = e;
 38     l->length++;
 39     return OK;
 40 }
 41 /*
 42  * 输出顺序表所有结点的值
 43  */
 44 int sequeuelist_print(struct sequeuelist *l) {
 45 
 46 
 47     int *start = NULL;
 48     int *stop = NULL;
 49 
 50     stop = &(l->elem[l->length]);
 51     for (start = &(l->elem[0]); start< stop; start++) {
 52         printf("%d\t", *start);
 53     }
 54     printf("\n");
 55 }
 56 
 57 /*
 58  * 顺序表l,从第i各元素起,连续删除k个元素。
 59  */
 60 int sequeuelist_delete_ith_to_kth(struct sequeuelist *l, int i, int k)
 61 {
 62         int *p = NULL;/*如果p为指向struct squeue的指针类型,则p++后,p增加的是struct squeue类型成员的长度*/
 63         int *q = NULL;
 64         int *r = NULL;
 65         int length_temp = l->length-1;
 66         p = &(l->elem[i-1]);
 67         r = &(l->elem[length_temp]);
 68         for (q = &(l->elem[i+k-1]); q <= &(l->elem[length_temp]); /*q++*/) {
 69                 *(p++) = *q;
 70                 q++;
 71                 l->length--;
 72         }
 73 
 74         return OK;
 75 }
 76 /*
 77  *
 78  */
 79 int main(void) {
 80     int i;
 81     int e;
 82     int n = 10;
 83     struct sequeuelist *l = NULL;
 84     struct sequeuelist M;
 85     l = &M;
 86 
 87     sequeuelist_init(l);
 88     printf("Please input n numbers:\n");
 89     /*
 90      * 由于线性表的下标是从0开始的
 91      */
 92     for (i = 1; i <= n; i++) {/* 创建初始的顺序表,包含n个数 */
 93         scanf("%d", &e);
 94         sequeuelist_insert(l, i, e);
 95     }
 96     sequeuelist_print(l);/*输出各结点的值*/
 97     ///*
 98     //sequeuelist_insert(l, 3, 999);/*在第三个元素前插入999*/
 99     //printf("After insert:\n");
100     //*/
101     //sequeuelist_print(M);/*输出插入后各结点的值*/
102     sequeuelist_delete_ith_to_kth(l, 3, 4);
103     sequeuelist_print(l);
105 return 0; 106 }

 

posted @ 2015-07-31 09:13  drfxiaoliuzi  阅读(246)  评论(0编辑  收藏  举报