C语言数据结构——线性表

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
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100

typedef int ElemType;
//增加代码的灵活性,让data的类型更灵活。

typedef struct{
ElemType *data;
int length;
}SeqList;

SeqList* initList()
{
SeqList *L = (SeqList*)malloc(sizeof(SeqList));
L->data = (ElemType*)malloc(sizeof(ElemType) * MAXSIZE);
L->length = 0;
return L;
}
//初始化

int appendList(SeqList *L,ElemType e)
{
if(L->length>MAXSIZE)
{
printf("FULL");
return 0;
}
L->data[L->length]=e;
L->length++;
return 1;
}
//线性表末尾增加数据

void listSeq(SeqList *L)
{
for(int i=0;i<=L->length-1;i++)
{
printf("%d ",L->data[i]);//
}
printf("\n");
}
//遍历

int insertList(SeqList *L,int pos,ElemType e)
{
if(pos>L->length)
{
printf("NO");
return 0;
}
for(int i=L->length-1;i >= pos-1;i--)
{
L->data[i+1]=L->data[i];
}
L->data[pos-1]=e;
L->length++;
return 1;
}
//指定位置插入指定数据

int deleteList(SeqList *L,int pos,ElemType *e)
{
*e =L->data[pos-1];
if(pos<L->length)
{
for(int i=pos;i<=L->length-1;i++)
{
L->data[i-1]=L->data[i];
}
}
printf("%d\n",*e);
L->length--;
return 1;
}
//指定位置删除数据并返回数据

int findList(SeqList *L,ElemType e)
{
for(int i=0;i <= L->length-1;i++)
{
if(L->data[i]==e)
{
printf("%d\n",i+1);
return 1;
}
}
return 0;
}
//查找数据第一次出现位置

int main()
{
int a;
SeqList *list=initList();
appendList(list,12);
appendList(list,34);
appendList(list,23);
appendList(list,17);
listSeq(list);
findList(list,17);
insertList(list,2,16);
listSeq(list);
deleteList(list,3,&a);
listSeq(list);
free(list->data);
free(list);
return 0;
}