数据结构——线性表的实现(增删部分)

来源:互联网 发布:手机淘宝购物流程 编辑:程序博客网 时间:2024/05/18 23:58
#include<stdio.h>#include<stdlib.h>#define LIST_INIT_SIZE 10#define LISTINCREMENT 10typedef int ElemType;typedef int Status;typedef struct {    ElemType *elem;    int length;//当前长度    int listsize;//当前分配的存储容量}SqList;Status InitList_Sq(SqList &L) {    L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));    if (!L.elem)exit(0);    L.length = 0;    L.listsize = LIST_INIT_SIZE;    return 1;}Status ListInsert_Sq(SqList &L, int i, ElemType e) {    ElemType* newbase;    if (i<1 || i>L.length + 1)return 0;    if (L.length >= L.listsize) {        newbase = (ElemType *)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(ElemType));        if (!newbase)exit(2);        L.elem = newbase;        L.listsize += LISTINCREMENT;    }    ElemType* p = 0, *q = 0;    q = &(L.elem[i - 1]);    for (p = &(L.elem[L.length - 1]); p >= q; --p)        *(p + 1) = *p;    *q = e;    ++L.length;    return 1;    //0代表i值不合法,1代表成功,2代表存储再分配失败}Status ListDelete_Sq(SqList &L, int i) {    if ((i < 1) || (i > L.length+1))return 0;    ElemType e;    ElemType * p;    ElemType *q;    p = &(L.elem[i - 1]);    e = *p;//e是删除的值    q = L.elem + L.length - 1;//表尾的元素    for (++p; p <= q; ++p)        *(p - 1) = *p;    --L.length;    return e;    //0代表i值不合法,非零代表有可能已经成功}void main() {    SqList s;    int flag = 100;    flag = InitList_Sq(s);    printf("当flag为1时代表成功,初始化结果为\t\t%d\t指针首地址为%ld\n", flag, s.elem);    flag = ListInsert_Sq(s, 1, 10);    printf("当flag为1时代表成功,添加结果为\t\t\t%d\t添加的数为%ld\t此数组长度为%d\n", flag, *s.elem,s.length);    flag = ListInsert_Sq(s, 2, 100);    printf("当flag为1时代表成功,添加结果为\t\t\t%d\t添加的数为%ld\t此数组长度为%d\n", flag, *(s.elem+1), s.length);    flag = ListDelete_Sq(s, 2);    printf("当flag为非零时代表可能已经成功,删除结果为\t%d\t删除的数为%ld\t此数组长度为%d\n", flag, flag, s.length);}

主要知识点:
1.初始化内存分配
L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
2.内存再分配
newbase = (ElemType )realloc(L.elem, (L.listsize + LISTINCREMENT) sizeof(ElemType));
3.insert部分如何实现插入点后的元素后移
4.delete部分如何实现删除点后的元素前移
5.在一个有n个元素的线性表中,插入或删除平均移动n/2个元素,这两部分平均时间复杂度为O(n)

原创粉丝点击