1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
|
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct
{
int *elem; /*线性表的基地址*/
int length; /*线性表当前的长度*/
int listsize; /*线性表当前分配的存储容量*/
} SeqList;
int InitSeqList(SeqList *L, int LISTINITSIZE); /*顺序表初始化*/
int InsertSeqList(SeqList *L, int i, int e); /*插入运算*/
int DeleteSeqList(SeqList *L, int i); /*删除运算*/
int SearchSeqList(SeqList *L, int x); /*按值查找*/
void traverseSeqList(SeqList *L); /*遍历*/
int InitSeqList(SeqList *L, int LISTINITSIZE)
{ /*LIST_INIT_SIZE表示最初分配给线性表的存储空间(线性表容量)*/
L->elem = (int*)malloc(LISTINITSIZE * sizeof(int));
if (!L->elem)
return 0;
L->length = 0;
L->listsize = LISTINITSIZE;
return 1;
}
int InsertSeqList(SeqList *L, int i, int e)
{ /*初始条件:顺序线性表L已存在,1≤i≤ListLength(L)+1*/
/*操作结果:再L中第i个位置之前插入新的数据元素e,L的长度加1*/
int *q, *p;
if (i < 1 || i > L->length + 1)
return 0;
else if (L->length >= L->listsize)
{
printf("顺序表已满");
return 0;
}
else
{
q = L->elem + i;
for (p = L->elem + L->length; p >= q; --p)
*(p + 1) = *p;
*q = e;
++L->length;
return 1;
}
}
int DeleteSeqList(SeqList *L, int i)
{ /*初始条件:顺序线性表L已存在,1≤i≤ListLength(L)*/
int j;
if (i < 1 || i > L->length)
{
printf("不存在第i个元素!\n");
return 0;
}
else
{
for (j = i; j < L->length; j++)
L->elem[j] = L->elem[j + 1]; /*向上顺序移动元素*/
L->length--; /*表长减1*/
return 1;
}
}
int SearchSeqList(SeqList *L, int x)
{
int j = 1;
while (j <= L->length && L->elem[j] != x)
j++;
if (j > L->length)
return -1;
else
return j;
}
void traverseSeqList(SeqList *L)
{
int i;
for ( i = 1; i <= L->length; i++)
{
printf("位置%d:%d, ",i,L->elem[i]);
}
}
int main()
{
int n = 1, a, b, c, goal, num, delGoal, numGoal, result;
SeqList L; // 修正指针问题
while (n)
{
printf("输入选择:\n1——建立顺序表,长度为20;\n2——插入元素\n3——删除元素\n4——按值查找\n5——遍历\n0——退出\n");
scanf("%d", &n);
switch (n)
{
case 1:
if (a = InitSeqList(&L, 50)) // 传入地址
printf("创建成功\n");
break;
case 2:
printf("输入目标位置\n");
scanf("%d", &goal);
printf("输入目标值\n");
scanf("%d", &num);
if (b = InsertSeqList(&L, goal, num))
printf("插入成功\n");
else
printf("插入失败\n");
break;
case 3:
printf("输入要删除的位置\n");
scanf("%d", &delGoal);
if (c = DeleteSeqList(&L, delGoal))
printf("删除成功\n");
else
printf("删除失败\n");
break;
case 4:
printf("输入查找目标值\n");
scanf("%d", &numGoal);
result = SearchSeqList(&L, numGoal);
if (result != -1)
printf("目标位置为%d\n", result);
else
printf("未找到目标值\n");
break;
case 5:
traverseSeqList(&L);
break;
case 0:
return 0;
default:
printf("无效选项,请重新输入。\n");
break;
}
}
}
|