2.顺序表的插入操作

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <malloc.h>
 4 
 5 #define OK   1
 6 #define ERROR  0
 7 #define TRUE 1
 8 #define FALSE 0
 9 
10 #define ElemType int
11 #define    MAXSIZE  100   /*此处的宏定义常量表示线性表可能达到的最大长度*/
12 typedef  struct
13 
14     ElemType  elem[MAXSIZE];  /*线性表占用的数组空间*/
15     int       last;    /*记录线性表中最后一个元素在数组elem[ ]中的位置(下标值),空表置为-1*/
16 }SeqList;
17 
18 /*在顺序表L中第i个数据元素之前插入一个元素e。 插入前表长n=L->last+1,i的合法取值范围是 1≤i≤L->last+2  */
19 int  InsList(SeqList *L,int i,ElemType e)
20 
21     int k;
22     if((i<1|| (i>L->last+2)) /*首先判断插入位置是否合法*/
23     {
24         printf("inserted a error place!");
25         return(ERROR);
26     }
27     if(L->last>= MAXSIZE-1)
28     {
29         printf("The stack if full,can not insert!");
30         return(ERROR);
31     }
32     for(k=L->last;k>=i-1;k--)   /*为插入元素而移动位置*/
33         L->elem[k+1]=L->elem[k];
34     L->elem[i-1]=e;   /*在C语言数组中,第i个元素的下标为i-1*/
35     L->last++;
36     return(OK);
37 }
38 
39 void main()
40 {
41     SeqList *l;
42     int p,q,r;
43     int i;
44     l=(SeqList*)malloc(sizeof(SeqList));
45     printf("please insert the length of stack:");
46     scanf("%d",&r);
47     l->last = r-1;
48     printf("please input the number of the stack:\n");
49     for(i=0; i<=l->last; i++)
50     {
51         scanf("%d",&l->elem[i]);
52     }
53     printf("please input the place where you want to insert:\n");
54     scanf("%d",&p);
55     printf("please input the number which you want to insert:\n");
56     scanf("%d",&q);
57     InsList(l,p,q);
58     for(i=0; i<=l->last; i++)
59     {
60         printf("%d  ",l->elem[i]);
61     }
62 }
63 

posted @ 2009-07-15 00:15  清山博客  阅读(1777)  评论(0编辑  收藏  举报