- #define ERROR 0
- #define OK 1
- #define STUNUM 50
- #include <stdio.h>
- #include <string.h>
- struct STU
- {
- char name[20];
- char stuno[10];
- int age;
- int score;
- }stu[STUNUM];
- typedef struct LIST
- {
- struct STU stu[STUNUM];
- int length;
- }list, *plist;
- void printlist(list l)
- {
- int i;
- printf("name /tstuno /tage /tscore/n");
- for(i=0; i<l.length; i++)
- printf("%8s /t%s /t%d /t%d/n",
- l.stu[i].name,
- l.stu[i].stuno,
- l.stu[i].age,
- l.stu[i].score);
- printf("/n");
- }
- int listinsert(plist l, int i, struct STU e)
- {
- struct STU *p, *q;
- // cannot out of array
- if (i<1 || i > l->length+1)
- return ERROR;
- // array is full
- if(l->length >= STUNUM)
- {
- printf("full/n");
- return ERROR;
- }
- // get the pos to insert
- q = &(l->stu[i-1]);
- // init first
- if (0 == l->length)
- {
- *q = e;
- ++l->length;
- return OK;
- }
- // move from the last available to insert pos (with)
- for(p = &l->stu[l->length-1]; p>=q; --p)
- *(p+1) = *p;
- // assign it
- *q = e;
- // increase length
- ++l->length;
- return OK;
- }
- int main()
- {
- struct STU e;
- list l;
- memset(&l, 0, sizeof(list));
- l.length = 0;
- int i;
- strcpy(e.name, "gnuser");
- strcpy(e.stuno, "10000");
- for(i=0; i<10; i++)
- {
- e.age = 10;
- e.score = i;
- listinsert(&l, 1, e);
- }
- e.score = 11;
- listinsert(&l, 5, e);
- printf("List length now is%d./n/n", l.length);
- printlist(l);
- return 0;
- }
-
关键点是插入时的移动,插一个要移动当前位置以及以后已经存在的元素,但按照索引查询很方便
- printf("the 5th stu's record:/n");
- printf("%d/n", l.stu[4].score);