顺序表的初始化、插入、删除

昨天晚上做了中移动苏州软件公司的暑期实习岗的笔试题,感觉备受打击,尤其是自以为是的数据结构题(从快排、归并排序、堆排序中选一种实现),碎决定再次学习数据结构一次,并将重要的数据结构用程序实现。
这里先实现的是顺序表的初始化,插入和删除操作。

#include<iostream>
using namespace std;
// - - - - 线性表的动态分配顺序存储结构 - - - - 
#define LIST_INIT_SIZE 100  //存储空间的初始分配量
#define INCREMENT 10        //存储空间的分配增量
#define ElemType char

typedef struct{
    //线性表的存储结构
    ElemType *elem;   //存储空间基地址
    int length;       //当前长度
    int listsize;     //当前分配的存储容量
}SqList;

//线性表的初始化
int InitList_Sq(SqList *L){
    L->elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));//动态分配存储空间
    if (L->elem == NULL)
        return 0;
    L->length = 0;
    L->listsize = LIST_INIT_SIZE;
    return 0;
}

int ListInsert_Sq(SqList *L, int i, ElemType e){
    //在顺序表L的第i个位置之前插入元素e
    if (i<1 || i>L->length + 1)
        cout << "i值不合法" << endl;
    if (L->length >= L->listsize){    //当前空间已满,增加分配
        ElemType *newbase = (ElemType *)realloc(L->elem, (L->listsize + INCREMENT)*sizeof(ElemType));
        if (newbase = NULL){
            cout << "分配失败" << endl;
            return 0;
        }
        L->elem = newbase;      //新基地址
        L->listsize += INCREMENT;//增加存储容量
    }
    ElemType *q = &(L->elem[i - 1]);//q为插入位置
    for (ElemType *p = &(L->elem[L->length - 1]); p >= q; --p)
        *(p + 1) = *p;    //插入位置及其后的元素右移

    *q = e; //插入元素
    +L->length; //表长加1
    return 1;
}

int ListDelete_Sq(SqList *L, int i, ElemType *e){
    //顺序表中删除第i个元素,并用e返回其值
    if (i<1 || i>L->length + 1){          //i的合法值为1length
        cout << "i值不合法" << endl;
        return 0;
    }
    ElemType *p = &(L->elem[i - 1]);  //p为被删除的元素的位置
    *e = *p; //把p的值赋给e
    ElemType *q = L->elem + L->length - 1;//表尾元素的位置
    for (++p; p <= q; ++p)
        *(p - 1) = *p;
    --L->length;
    return 0;
}

int main(){
    SqList L;
    InitList_Sq(&L);
    for (int i = 0; i < 22; i++)
        ListInsert_Sq(&L, 1, 'a' + i);
    ElemType e;
    ListDelete_Sq(&L, 10, &e);
    cout << "删除的元素是" << e;

    for (int j = 0; j < L.length; j++)
        cout << L.elem[j];
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiakejiang/article/details/51583501
今日推荐