数据结构-顺序表的代码笔记

浙江大学数据结构mooc笔记

 1 //
 2 //  顺序表.cpp
 3 //  顺序表
 4 //
 5 //  Created by loglian on 2020/4/21.
 6 //  Copyright © 2020 loglian. All rights reserved.
 7 //
 8 //线性表
 9 #include <stdio.h>
10 #include <stdlib.h>    //malloc函数头文件
11 #define MAXSIZE 100
12 typedef struct LNode *List;
13 typedef int ElementType;
14 struct LNode{
15     ElementType Data[MAXSIZE];  //定义一个数组 分量类型为ElementType
16     int Last;   //线性表最后一个元素
17 };
18 struct LNode L; //访问下标为i的元素:L.data[i] 或 Ptrl->Data[i]
19 List Ptrl;  //Ptrl为指针   //线性表长度 L.Last+1 或 Ptrl->Last+1
20 
21 
22 //初始化建立空的顺序表
23 List MakeEmpty()
24 {   List Ptrl;  //指针
25     Ptrl = (List)malloc(sizeof(struct LNode));  //通过malloc函数申请一个结构
26     Ptrl->Last = -1;    //Last代表最后一个元素  当Last为0则有一个元素在第一个位置
27     return Ptrl;    //没元素则设为-1
28 }
29 
30 
31 //查找    //查找成功的平均比较次数为(n+1)/2   平均时间性能为O(n)
32 int Find(ElementType X,List Ptrl)
33 {
34     int i=0;
35     while (i<=Ptrl->Last&&Ptrl->Data[i]!=X)
36         i++;
37     if(i>Ptrl->Last)    return -1;
38     else return i;
39 }
40 
41 
42 //插入    先移动 后插入     1表满? 2位置合法? 3移动插入
43 //查找成功的平均比较次数为n/2   平均时间性能为O(n)
44 void Insert(ElementType X,int i,List Ptrl)  //X插入到第i个位置
45 {
46     int j;
47     if(Ptrl->Last==MAXSIZE-1)   //表空间已满m,无法插入
48      {                          //数组下标从0开始所以最后一个元素下标为MAXSIZE
49         printf ("表满");
50         return;
51     }
52     if(i<1||i>Ptrl->Last+2)
53     {
54         printf ("位置不合法");
55         return;
56     }
57     for(j=Ptrl->Last;j>=i-1;j--)    //将i-1后的元素全部后移
58     {
59         Ptrl->Data[j+1]=Ptrl->Data[j];
60     }
61     Ptrl->Data[i-1]=X;  //插入新元素
62     Ptrl->Last++;   //Last仍然指向最后元素
63     return;
64     
65 }
66 
67 
68 //删除
69 //查找成功的平均比较次数为(n-1)/2   平均时间性能为O(n)
70 void Delete(int i,List Ptrl)
71 {
72     int j;
73     if(Ptrl->Last==-1)   //表空间已满m,无法插入
74      {                          //数组下标从0开始所以最后一个元素下标为MAXSIZE
75         printf ("表空");
76         return;
77     }
78     if(i<1||i>Ptrl->Last+1)
79     {
80         printf ("%d位置不合法",i);
81         return;
82     }
83     for(j=i;j<=Ptrl->Last;j++)
84     {
85         Ptrl->Data[j-1]=Ptrl->Data[j];
86     }
87     Ptrl->Last--;
88     return;
89 }
原文地址:https://www.cnblogs.com/loglian/p/12778554.html