线性表的顺序操作

栏目: 数据库 · 发布时间: 6年前

#include <stdio.h>

#define maxsize 10
#define failure -1
#define success 1
typedef int datatype;

typedef struct {
    datatype data[maxsize];
    int length;
} Seqlist;

typedef Seqlist* List;

///求表长度 o(1)
int length(Seqlist L) {
    return L.length;
}

/// 取表元 O(n)
datatype get(List L, int index) {
    if (index < 1 || index > L->length ) {
        return failure;
    }
    return L->data[index - 1];
}

/// 定位 O(n)
int locate(List L, datatype x) {
//    for (int i = 0; i < L->length - 1; i++) {
//        if (x == L->data[i]) {
//            return i + 1;
//        }
//    }
//    return failure;
    int i = 0;
    while (i < L->length && L->data[i] != x) {
        i++;
    }
    if (i < L->length) {
        return i + 1;
    } else {
        return failure;
    }
}

/// 删除 O(n)
int delete(List L, int index) {
    if (index < 1 || index > L->length) {
        return failure;
    }
    for (int j = index; j < L->length; j++) {
        L->data[j - 1] = L->data[j];
    }
    return success;
}

/// 插入 O(n)
int insert(List L, datatype x, int index) {
    
    if (L->length == maxsize) {
        return failure; //表满
    }
    if (index < 1 || index > L->length + 1) {
        return failure; //位置错
    }
    
    for (int j = L->length; j >= index; j--) {
        L->data[j] = L->data[j - 1];
    }
    L->data[index - 1] = x;
    L->length++;
    return success;
}



int main(int argc, const char * argv[]) {
    List L = (List)malloc(sizeof(Seqlist));
    L->length = 0;
    printf("%d\n", length(*L));
    int result = insert(L, 0, 1);
    printf("%d\n", result);
    printf("%d\n", length(*L));
    
    printf("取表元 %d\n", get(L, 0));
    return 0;
}

--EOF--


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTML5与CSS3基础教程(第7版)

HTML5与CSS3基础教程(第7版)

[美] Elizabeth Castro、[美] Bruce Hyslop / 望以文 / 人民邮电出版社 / 2013-1 / 59.00元

代表下一代网页编写技术的HTML5,为网页提供布局和格式的CSS3,这两者构成了Web开发的基石,也是Web程序员和设计师必须熟练掌握的最基本技能。 本书是风靡全球的HTML和CSS最佳入门教程的最新版,上一版单单英文版的销量就超过100万册,被翻译为十多种语言,并长期雄踞亚马逊书店计算机图书排行榜榜首。 最新的第7版秉承前一版直观、透彻、全面、循序渐进的讲授特色,仍然采用独特的双栏图......一起来看看 《HTML5与CSS3基础教程(第7版)》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具