zoukankan      html  css  js  c++  java
  • 线性表

    /**
     * 线性表
     **/
    #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;
    }
  • 相关阅读:
    201521123093 java 第二周学习总结
    201521123093 java 第一周总结
    Word 2010怎么自动添加文献引用
    动态链接库(dll)文件的动态调用(使用动态链接库,解析Wis文件--测井数据文件的一种)
    open inventor 学习笔记
    井眼轨迹的三次样条插值 (vs + QT + coin3d)
    VS2010 + QT 5 +open inventor 环境配置
    我的第一个项目(人力资源管理之报表管理)
    B-tree 和 B+tree
    mysql count(*)与count(1)的区别
  • 原文地址:https://www.cnblogs.com/hnhcc39/p/2923621.html
Copyright © 2011-2022 走看看