线性表

/**
 * 线性表
 **/
#include "stdio.h"
#include <stdlib.h>
#include <iostream.h>

#define LIST_MAX_LENGTH 100     //线性表的最大长度
#define OK 1
#define ERROR 0

//定义线性表结构
typedef struct{
    int  *item;                //指向存放线性表中数据元素的基地址
    int  length;            //线性表的当前长度                                                      
}SQ_LIST;

//初始线性表
int init(SQ_LIST *L)
{
    L->item=(int*)malloc(LIST_MAX_LENGTH*sizeof(int));  //分配空间
    if (L->item==NULL)  return ERROR;    //若分配空间不成功,返回ERROR
    L->length=0;                         //将当前线性表长度置0
    return OK;                           //成功返回OK
}

//返回线性表长度
int length(SQ_LIST L)
{
    return L.length;
}

//销毁线性表
void destroy(SQ_LIST *L)
{
  if (L->item) free(L->item);        //释放线性表占据的所有存储空间
}

//清空线性表
void clear(SQ_LIST *L) 
{
   L->length=0;                        //将线性表的长度置为0
}

//查找对应的元素
int getItem(SQ_LIST L,int i,int *e)
{
    if(i<1 || i>L.length)
    {
        return ERROR;
    }
    *e = L.item[i-1];
    return OK;
}

//检索e的位置
int getLocate(SQ_LIST L,int e)
{
    for(int i=0;i<L.length;i++)
    {
        if(L.item[i] == e) return i+1;
    }
    return 0;
}

//第i个元素前插入e
int insertList(SQ_LIST *L, int i, int e)
{
    //如果线性表已经满了
    if(L->length==LIST_MAX_LENGTH) return ERROR;

    if(i<1 || i>L->length+1) return ERROR;

    for(int j=L->length-1;j>=i-1;j--)
    {
        L->item[j+1] = L->item[j];
    }
    L->item[i-1] = e;
    L->length++;
    return OK;
}

//第i个元素删除
int deleteList(SQ_LIST *L, int i, int *e)
{
    if(i<1 || i>L->length+1) return ERROR;
    *e = L->item[i-1];
    for(int j=i;j<L->length-2;j++)
    {
        L->item[j-1] = L->item[j];
    }
    L->length--;
    return OK;
}

//插入线性表
void insert(SQ_LIST *L)
{
    cout<<"请依次递增输入这5个数据:"<<endl;
    for(int i=0;i<5;i++)
    {
        cin>>L->item[i];
        L->length++;
    }
}

//输出线性表
void print(SQ_LIST *L)
{
    cout<<"输出的结果是:";
    for(int i=0;i<L->length;i++)
    {
        cout<<L->item[i]<<"  ";
    }
    cout<<endl;
}
原文地址:https://www.cnblogs.com/hnhcc39/p/2923621.html