• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C++顺序存储的线性表

OC/C/C++ 水墨上仙 2929次浏览

C++顺序存储的线性表
来源:http://blog.csdn.net/creazyapple/article/details/7931830

/*
 * 顺序存储的线性表
 */
#include <stdio.h>
#define OK 1
#define ERR 0
#define LIST_INIT_SIZE 100
#define LIST_INCREMENT 10
#define ElemType char
typedef struct {
    ElemType *elem;
    int length;//元素个数
    int listSize;//总容量
} SqList;
int InitList(SqList *aList)
{
    aList->elem = (ElemType *)malloc(sizeof(ElemType)*LIST_INIT_SIZE);
    if(NULL == aList->elem)return ERR;
    aList->listSize = LIST_INIT_SIZE;
    aList->length = 0;
    return OK;
}
int ListInsert(SqList *aList,ElemType e,int index)
{
    int i;
    if( index<0 || index>aList->length ){
        printf("Error : Insert %c to wrong position %d\n",e,index);
        return ERR;//中间不允许存在空位
    }
    if( aList->listSize <= aList->length )
    {
        aList->elem = (ElemType *)realloc(aList->elem,
                            sizeof(ElemType)*aList->listSize+LIST_INCREMENT);
        if(NULL == aList->elem) return ERR;
        aList->listSize += LIST_INCREMENT;
    }
    printf("Insert %c to position %d\n",e,index );
    i = aList->length;
    while(i>index)
    {
        aList->elem[i] = aList->elem[i-1];
        i--;
    }
    aList->elem[index] = e;
    aList->length++;
    return OK;
}
int ListDelete(SqList *aList,ElemType *e,int index)
{
    int i = index;
    if(i<0 || i>=aList->length)return ERR;
    *e = aList->elem[index];
    i = index;
    while(i<aList->length-1)
    {
        aList->elem[i] = aList->elem[i+1];
        i++;
    }
    aList->length--;
    return OK;
}
int ListTraverse(SqList aList)
{
    int i=0;
    while(i < aList.length){
        printf("%c\t",aList.elem[i]);
        i++;
    }
    printf("\n");
    return OK;
}
int main(int argc, char *argv[])
{
    SqList aList ;
    char element;
    int position;
    InitList( &aList );
    while(1){
        printf("Please input element and position to insert in (input ; to quit) :\n");
        scanf("%1s,%d",&element,&position);
        if(';' == element) break;
        ListInsert(&aList,element,position);
    }
    ListDelete(&aList,&element,0);
    ListTraverse(aList);
    printf("length :%d . \n",aList.length);
    return OK;
}


喜欢 (0)
加载中……