标签:
1 1. 数组定义:
2
3 typedef struct SqList
4 {
5 ElemType list[MaxSize];
6 int size;
7 } SqList;
8
9 2. 指针定义:
10
11 typedef struct SqList
12 {
13 ElemType *elem;
14 int length;
15 int listsize;
16 } Sqlist;
17
18 3. 完整代码
19
20 #include <stdio.h>
21 #include <malloc.h>
22 #include <process.h>
23
24 #define LIST_INIT_SIZE 100
25 #define LISTINCREMENT 10
26
27 #define OK 1
28 #define ERROR 0
29 #define OVERFLOW -2
30
31 typedef int Status;
32 typedef int ElemType;
33
34 typedef struct
35 {
36 ElemType *elem;
37 int length;
38 int listsize;
39 } SqList;
40
41 //创建空顺序表
42 Status InitList_Sq( SqList &L )
43 {
44 L.elem = (ElemType*) malloc (LIST_INIT_SIZE*sizeof(ElemType));
45 if (!L.elem)
46 exit(OVERFLOW);
47 L.length = 0;
48 L.listsize = LIST_INIT_SIZE;
49 return OK;
50 }
51
52 //顺序表在第i个元素之前插入e
53 Status ListInsert_Sq( SqList &L, int i, ElemType e)
54 {
55 ElemType *newbase,*q,*p;
56 if(i<1 || i>L.length+1) //插入位置非法
57 return ERROR;
58
59 if(L.length>=L.listsize)//溢出,动态追加空间
60 {
61 newbase= (ElemType *)realloc(L.elem, (L.listsize+ LISTINCREMENT) *sizeof(ElemType));
62 if(!newbase) exit(OVERFLOW);
63 L.elem=newbase;
64 L.listsize+=LISTINCREMENT;
65 }
66 q=&(L.elem[i-1]);
67 for(p=&(L.elem[L.length-1]); p>=q; p--) //元素后移
68 *(p+1)=*p;
69 *q=e; //完成元素插入
70 ++L.length;
71 return(OK);
72 }
73
74
75 //顺序表遍历显示
76 Status ListTraverse_Sq(SqList L)
77 {
78 int i=0;
79 if(!L.elem)
80 return ERROR;
81 while(i<L.length)
82 printf("%d ",L.elem[i++]);
83 printf("\n");
84 return OK;
85 }
86 //顺序表逆置
87 void Reverse_Sq(SqList &L)
88 {
89 int i,j;
90 ElemType temp;
91 for(i=0,j=L.length-1; i<j; i++,j--)
92 {
93 temp=L.elem[i];
94 L.elem[i]=L.elem[j];
95 L.elem[j]=temp;
96 }
97 }
98 int main()
99 {
100 SqList L;
101 char flag;
102 int i;
103 ElemType e;
104 if(InitList_Sq(L)==OK)
105 {
106 printf("建立空顺序表成功!\n");
107 do
108 {
109 printf("当前线性表长度为:%d\n",L.length);
110 printf("请输入要插入元素的位置:");
111 scanf("%d",&i);
112 printf("请输入要插入的元素值:");
113 scanf("%d",&e);
114 if(ListInsert_Sq(L,i,e)==OK)
115 {
116 printf("插入成功,插入后顺序表长度为:%d\n",L.length);
117 printf("插入后的顺序表为:");
118 ListTraverse_Sq(L);
119 }
120 else
121 printf("插入失败");
122 printf("\n继续插入元素?(y/n) ");
123 fflush(stdin);
124 scanf("%c",&flag);
125 }
126 while(flag==‘y‘);
127
128 Reverse_Sq(L);
129 printf("顺序表逆置后为:\n");
130 ListTraverse_Sq(L);
131 }
132 else
133 printf("顺序表初始化失败!\n");
134 }
标签:
原文地址:http://www.cnblogs.com/htmlphp/p/4889307.html