数据结构之线性表

零个或多个数据元素的有效限序列

首先它是一个序列,元素之间是有序的,若元素存在多个,则第一个元素无前驱,最后一个元素无后继,其他元素有且只有一个前驱和后继

头文件

#ifndef _SEQUENCELIST_H             
#define _SEQUENCELIST_H                  //自定义库函数

#define SIZE        10                   //宏定义 
#define SUCCESS     10000
#define FAILURE     10001

typedef int ElemType;                     //为int数据类型定义新名字

struct SequenceList                       //结构体
{
    int length;
    ElemType *data;
};                                        // ;不可丢

typedef struct SequenceList SeList;

int SequenceInit(SeList *l);
int SequenceInsrt(SeList *l, int p, ElemType e);

#endif

自定义函数

#include <stdio.h>
#include <stdlib.h>
#include "SequenceList.h"                  //头文件中自定义的库函数

int SequenceInit(SeList *l)                //传过来的是地址,接收要用指针
{      
    if(NULL == l)                           //入参判断
    {
        return FAILURE;
    }

    l->length = 0;                          //长度初始值为0     

    return SUCCESS;
}

int SequenceInsrt(SeList *l, int p, ElemType e)
{
    int i;

    if(NULL == l)
    {
        return FAILURE;
    }
    if(p > l->length + 1 || l->length >= SIZE || p < 1)        //p有意义的条件
    {
        return FAILURE;
    }

    for(i = 0; i < l->length - p + 1; i++)              //从插入的地方依次向后移实现插入
    {
        l->data[l->length - i] = l->data[l->length - i - 1];
    }

    l->data[p - 1] = e;
    l->length++;                          //插入一个元素后,结构体的长度发生了变化

    return SUCCESS;
}

 主函数

#include <stdio.h>
#include <stdlib.h>
#include "SequenceList.h"
#include <time.h>

int main()
{
    int i, ret;
    SeList list;

    srand(time(NULL));

    ret = SequenceInit(&list);                  //要改变list里元素的值,所以要传地址

    if(ret == SUCCESS)
    {
        printf("Init Success!\n");
    }
    else
    {
        printf("Init Failure!\n");
    }
   
    for(i = 0; i < 5; i++)
    {
        ret = SequenceInsrt(&list, i + 1, rand() % 10);
        
        if(FAILURE == ret)
        {
            printf("Insert Failure!\n");
        }
        else
        {
            printf("Insert Success!\n");
        }
    }
    return 0;
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值