1 #define LIST_SIZE 80
2 #define LISTINCREMENT 10
3 #define ok 1
4 #define overflow -1
5 #define error -2
6 #include<stdio.h>
7 #include<stdlib.h>
8 typedef struct
9 {
10 int *elem;
11 int length;
12 int listsize;
13 }sqlist;
14 int initlist(sqlist &L)
15 {
16 L.elem=(int *)malloc(LIST_SIZE*sizeof(int));
17 if(!L.elem) exit(overflow);
18 L.length=0;
19 L.listsize=LIST_SIZE;
20 return ok;
21 }
22 int listinsert(sqlist &L,int i,int e)
23 {
24 int *p,*q,*newbase;
25 if(i<1||i>L.length+1) return error;
26 if(L.length>=L.listsize)
27 {
28 newbase=(int *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(int));
29 if(!newbase) exit(overflow);
30 L.elem=newbase;
31 L.listsize +=LISTINCREMENT;
32 }
33 q=&(L.elem[i-1]);
34 for(p=&(L.elem[L.length-1]);p>=q;--p) *(p+1)=*p;
35 *q=e;
36 ++L.length;
37 return ok;
38 }
39 int ListDelete(sqlist &L,int i,int &e)
40 {
41 int *p,*q;
42 if((i<1)||(i>L.length)) return(error);
43 p=&(L.elem[i-1]);
44 e=*p;
45 q=L.elem+L.length-1;
46 for(++p;p<=q;++p) *(p-1)=*p;
47 --L.length;
48 return ok;
49 }
50 void printlist(sqlist L)
51 {
52 int i;
53 printf("\n*********************");
54 printf("线性表元素如下:\n");
55 for(i=0;i<L.length;i++)
56 printf("%d ",L.elem[i]);
57 printf("\n*********************\n");
58 }
59 main()
60 {
61 int i,j,e;
62 sqlist L1;
63 initlist(L1);
64 printf("请输入线性表长度:\n");
65 scanf("%d",&L1.length);
66 printf("请输入线性表数据元素:\n");
67 for(i=0; i<L1.length; i++)
68 scanf("%d",&L1.elem[i]);
69 printlist(L1);
70 printf("请输入在线性表插入的位置和数据元素:\n");
71 scanf("%d%d",&j,&e);
72 listinsert(L1,j,e);
73 printlist(L1);
74 printf("请输入在线性表删除的位置:\n");
75 scanf("%d",&j);
76 ListDelete(L1,j,e);
77 printlist(L1);
78 system("pause");
79 }