线性表的顺序存储

参考自:http://blog.csdn.net/u010187139/article/details/46659943

//
//  main.c
//  SqlListDemo
//对其改变的传地址,对其使用读取的传
//  Created by zhanggui on 15/8/11.
//  Copyright (c) 2015年 zhanggui. All rights reserved.
//

#include <stdio.h>
//定义常量 存储空间的初始化分配
#define MAXSIZE 30
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define OK 1

//typedef定义类型
typedef int  Status;
typedef int ElemType;

//定义一个结构体:存储空间的其实位置,最大容量,当前长度
typedef struct {
    ElemType data[MAXSIZE];
    int length;
    }SqList;
//初始化函数
Status initList(SqList *L)
{
    L->length = 0;
    return 0;
}
//返回线性表的长度
Status getListLength(SqList L)
{
    return L.length;
}
//判断线性表是否为空,若空返回true,否则返回false
Status listIsEmpty(SqList L)
{
    if (L.length==0) {
        return TRUE;
    }
    return FALSE;
}
//线性表清空,长度为0
Status listEmpty(SqList *L)
{
    L->length = 0;
    return OK;
}
//获取指定的元素的值,返回下标为i-1的元素,赋值给e
Status getElem(SqList L,int i,ElemType *e)
{
    //判断元素位置是否合法
    if (i>L.length||i<1) {
        printf("查找位置不正确
");
        return ERROR;
    }
    //判断线性表是否为空
    if (listIsEmpty(L)) {
        return ERROR;
    }
    *e = L.data[i-1];
    return OK;
}
//在线性表中查找指定的e相等的元素,如果查找成功,返回元素下标,否则失败。
Status locateElem(SqList L,ElemType e)
{
    int i;
    for (i=0; i<L.length; i++) {
        if (L.data[i]==e) {
            return i;
        }
    }
    printf("没有查找到元素%d",e);
    return ERROR;
}
//自动创建一个MAXSIZE个元素,并赋值为0
Status createList(SqList *L)
{
    int i;
    for (i=0; i<MAXSIZE; i++) {
        L->data[i] = i;
    }
    L->length = MAXSIZE;
    return OK;
}
//在线性表第i个元素前插入新元素e
Status listInsert(SqList *L,int i,ElemType e)
{
    //判断长度是否可以允许插入新的数据
    if (L->length>=MAXSIZE) {
        printf("空间已满,不能再插入数据
");
        return FALSE;
    }
    //判断长度是否可以允许插入新数据
    if (i>L->length||i<1) {
        return FALSE;
    }
    int j;
    //从后边依次后移
    for (j=L->length-1; j>=i; j--) {
        L->data[j] = L->data[j-1];
    }
    L->data[i-1] = e;
    L->length++;
    return TRUE;
}
//删除线性表中第i个元素,成功后表长减一,用e返回其值
Status deleteList(SqList *L,int i,ElemType *e)
{
    //判断线性表为空
    printf("%d",listIsEmpty(*L));
    if (listIsEmpty(*L)) {
        return ERROR;
    }
    //判断删除位置是否合法
    if (i<1||i>L->length) {
        printf("删除位置不合法");
        return ERROR;
    }
    *e = L->data[i-1];
    
    for (; i<L->length; i++) {
        L->data[i-1] = L->data[i];
    }
    L->length--;
    return TRUE;
}
//遍历线性表
Status listTraverse(SqList L)
{
    int i;
    for (i=0; i<L.length; i++) {
        printf("%d ",L.data[i]);
    }
    printf("
");
    return OK;
}
int main(int argc, const char * argv[]) {
    SqList L;
    ElemType e;
    initList(&L);  //初始化
    createList(&L);  //创建
    printf("初始值:
");
    listTraverse(L);//遍历线性表
    deleteList(&L, 1, &e);
    printf("删除后的结果:
");
    listTraverse(L);
    listInsert(&L, 2, 3);
    printf("插入后的结果:
");
    listTraverse(L);
    return 0;
}

源码下载地址:http://pan.baidu.com/s/1jGnecSm

原文地址:https://www.cnblogs.com/zhanggui/p/4722507.html