c——线性表

线性表

定义:同一类型的数据元素构成的有序序列的线性结构

数组实现

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #define MAXSIZE 80
 4 typedef int ElementType;
 5 
 6 typedef struct LNode {
 7     ElementType Data[MAXSIZE];
 8     int Last;
 9 }*List;
10 
11 //创建新线性表
12 List MakeEmpty() {
13     List L;
14     L = (List)malloc(sizeof(struct LNode));
15     L->Last=-1;
16     return L;
17 }
18 //输出所有元素
19 void Print(List L) {
20     int i;
21     if(L->Last==-1) {
22         printf("空表");
23         return;
24     }
25     for(i=0;i<=L->Last;i++) {
26         printf("%d ",L->Data[i]);
27     }
28 }
29 //查找元素
30 int Find(ElementType X,List PtrL) {
31     int i = 0;
32     while(i<=PtrL->Last && PtrL->Data[i]!=X) i++;
33     if(i>PtrL->Last) return -1;
34     else return i;
35 }
36 //在第i个元素的位置插入新元素
37 void Insert(ElementType X,int i,List PtrL) {
38     int j;
39     //判断表是否满
40     if(PtrL->Last == MAXSIZE-1) {
41         printf("表满");
42         return;
43     }
44     //i是否在1~n+1范围内
45     if(i<1||i>PtrL->Last+2) {
46         printf("位置不合法");
47         return;
48     }
49     for(j=PtrL->Last; j>=i-1; j--)
50         PtrL->Data[j+1] = PtrL->Data[j];
51     PtrL->Data[i-1]=X;
52     PtrL->Last++;
53     return;
54 }
55 //删除第i个元素
56 void Delete(int i,List PtrL) {
57     int j;
58     if(i<1||i>PtrL->Last+1) {
59         printf("不存在第%d个元素",i);
60         return;
61     }
62     for(j=i; j<=PtrL->Last; j++)
63         PtrL->Data[j-1]=PtrL->Data[j];
64     PtrL->Last--;
65     return;
66 }
67 int main() {
68     List TestL;
69     TestL=MakeEmpty();
70     Insert(18,1,TestL);
71     Insert(19,2,TestL);
72     Insert(20,3,TestL);
73     Print(TestL);
74 }

分析:

1、线性表的数组实现,本质上就是数组+位置指针,其中位置指针通过一个变量实现

猜你喜欢

转载自www.cnblogs.com/cxc1357/p/10804011.html