zoukankan      html  css  js  c++  java
  • [算法] 线性表

    线性表

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

    数组实现

     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、线性表的数组实现,本质上就是数组+位置指针,其中位置指针通过一个变量实现

  • 相关阅读:
    关于SVN更新慢的解决方法
    用PS做法线,高光贴图的最简图文教程
    3dmax教程 人物+骨骼+蒙皮+动画教程
    django 模板视图,表单视图,各种视图
    django settings最佳配置
    groovy 弹出菜单
    python construct文档
    用powershell实现自动化操作
    如何用chrome扩展将网页变成黑底白字,用以保护视力
    打造基于CentOS7的xfce最简工作环境
  • 原文地址:https://www.cnblogs.com/cxc1357/p/10804011.html
Copyright © 2011-2022 走看看