线性表的创建(C)

main.c

#define _CRT_SECURE_NO_WARNINGS
#include "header.h"
#include "SqList.h"
void main(void) {
    SqList LA;  //建立线性表

     InitList_Sq(&LA);//初始化线性表

。。。。。。。。。。。。。。。。。//添加自己的程序代码

  
    while (1);
}

header.h

#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ok 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2

SqList.h

#include "header.h"

#define LIST_INIT_SIZE 100                                 //线性表储存空间的初始分配量

#define LISTINCREMENT 10                               //线性表储存空间的分配增量
typedef int ElemType;
typedef struct {
    ElemType *elem;                                              //储存空间基址
    int length;                                                         //当前长度
    int listsize;                                                        //当前分配的存储量(以sizeof(ElemType)为单位)
}SqList;
int  InitList_Sq(SqList *L) {
    L->elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
    if (!L->elem) exit(OVERFLOW);                        //储存分配失败
    L->length = 0;                                                 //空表长度为0
    L->listsize = LIST_INIT_SIZE;                          //初始储存容量
    return OK;
}
int ListInsert_Sq(SqList *L, int i, ElemType e) {    //在顺序线性表L中第i个位置之前插入新的元素e,
    ElemType *p, *q;                                               //i的合法值为1<=i<=ListLength_Sq(L)+1
    if (i<1 || i>L->length + 1) return ERROR;       //i值不合法
    if (L->length >= L->listsize) {                         //当前储存空间已满,增加分配
        ElemType *newbase = (ElemType *)realloc(L->elem,
            (L->listsize + LISTINCREMENT) * sizeof(ElemType));
        if (!newbase)  return  ERROR;                   //储存分配失败
        L->elem = newbase;                                         //新基址
        L->listsize += LISTINCREMENT;                      //增加存储容量
    }
    q = &(L->elem[i - 1]);                                           //q为插入位置
    for (p = &(L->elem[L->length - 1]); p >= q; --p) *(p + 1) = *p;  //插入位置及之后的元素右移
    *q = e;                                                                      //插入e
    ++L->length;                                                          //表长增1
    return OK;
}

猜你喜欢

转载自blog.csdn.net/shaung_yue/article/details/80410369