线性表的顺序操作

栏目: 数据库 · 发布时间: 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--


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

查看所有标签

猜你喜欢:

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

迷茫的旅行商

迷茫的旅行商

[美] William J. Cook / 隋春宁 / 人民邮电出版社 / 2013-10-1 / 49.00

假设一名旅行商打算拜访一张城市列表中的所有城市,每座城市只去一次,最后回到出发地。要怎么走才能让路线最短呢?这就是旅行商问题,乍一听很简单,在应用数学界却是一道研究极其热烈的难题,时至今日仍无人能解。本书中,William J. Cook将带领读者踏上一场数学之旅,跟随旅行商的脚步,从19世纪初爱尔兰数学家W. R. Hamilton最初定义该问题开始,一路奔向当今最前沿、最顶尖的解题尝试。 ......一起来看看 《迷茫的旅行商》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具