首页 > 代码库 > 自学数据结构——顺序线性表

自学数据结构——顺序线性表

胡乱写了一些代码

/*
 ============================================================================
 Name        : sqlist.c
 Author      :codecup
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 15
typedef int ElementType;

typedef struct {
    ElementType list[MAXSIZE];
    int curLen;
} SqList;

//初始化顺序表
void InitSqList(SqList *list) {
    list->curLen = 0;
}

//插入元素
int insert(SqList *list, int i, ElementType e) {
    int j;
    if (list->curLen == MAXSIZE) {
        printf("顺序表已满");
        return EXIT_FAILURE;
    }
    if (i < 0 || i > list->curLen) {
        puts("插入位置不合法");
        return EXIT_FAILURE;
    } else {
        for (j = list->curLen; j > i; j--) {
            list->list[j] = list->list[j - 1];
        }
        list->list[i] = e;
        list->curLen++;
        return EXIT_SUCCESS;
    }
}

//清空
void clear(SqList *list) {
    list->curLen = 0;
}

//获取顺序表长度
int length(SqList *list) {
    return list->curLen;
}

//删除元素
int delete(SqList *list, int i) {
    int j;
    if (i < 0 || i > list->curLen) {
        puts("删除位置不合法");
        return EXIT_FAILURE;
    } else {
        for (j = i; j > list->curLen; j++) {
            list->list[j] = list->list[j + 1];
        }
        list->curLen--;
        return EXIT_SUCCESS;
    }
}

//获取元素
ElementType get(SqList *list, int i) {
    if (i < 0 || i > list->curLen) {
        printf("第%d个元素不存在", i);
        exit(0);
    }
    return list->list[i];
}

int main(void) {
    SqList mylist;
    int len, i;
    ElementType e;
    InitSqList(&mylist);
    for (i = 0; i < 10; ++i) {
        insert(&mylist, i, i + 4);
    }
    len = length(&mylist);
    printf("元素个数:%d.\n", len);
    printf("请输入要查找的元素:\n");
    scanf("%d", &i);
    e = get(&mylist, i);
    printf("你要查找的元素是%d", e);
    return EXIT_SUCCESS;
}