List 简单实现

来源:互联网 发布:mac客户端的网游 编辑:程序博客网 时间:2024/06/05 19:22
#include <stdio.h>#include <stdlib.h>#include <string.h>// Data#define MAXLEN 100// data elementtypedef struct{    char key[10];    char name[20];    int age;}DATA;// Logical Structuretypedef struct{    DATA listData[MAXLEN+1];    int ListLen;}SLType;// init listvoid SLInit(SLType *SL){    SL->ListLen = 0;}// ST Lengthint SLLength(SLType *SL){    return (SL->ListLen);}// insertint SLInsert(SLType *SL, int n, DATA data){    int i;    if(SL->ListLen >= MAXLEN)    {        printf("full \n");        return 0;    }    if(n < 1 || n > SL->ListLen-1)    {        printf("insert NUM is Error!\n");        return 0;    }    for(i=SL->ListLen; i>=n; i--)    {        SL->listData[i+1] = SL->listData[i];    }    SL->listData[n] = data;    SL->ListLen++;    return 1;}// Addint SLAdd(SLType* SL, DATA data){    if(SL->ListLen >= MAXLEN)    {        printf("full \n");        return 0;    }    SL->listData[++SL->ListLen] = data;    return 1;}// deleteint SLDelete(SLType *SL, int n){    int i;    if(n < 1 || n > SL->ListLen-1)    {        printf("delete NUM is Error!\n");        return 0;    }    for(i=n; i<SL->ListLen; i++)    {        SL->listData[i] = SL->listData[i+1];    }    SL->ListLen--;    return 1;}// FindNUmDATA *SLFindByNum(SLType *SL, int n){    if(n < 1 || n > SL->ListLen+1)    {        printf("Find NUM is Error!\n");        return 0;    }    return &(SL->listData[n]);}// FindDataint SLFindByCont(SLType *SL, char *key){    int i;    for(i = 1; i <= SL->ListLen; i++)    {        if(strcmp(SL->listData[i].key, key) == 0)        {            return i;        }    }    return 0;}// Showint SLAll(SLType *SL){    int i;    for(i = 1; i <= SL->ListLen; i++)    {        printf("(%s,%s,%d)\n", SL->listData[i].key, SL->listData[i].name, SL->listData[i].age);    }    return 0;}int main(){    int i;    SLType SL;    DATA data;    DATA *pdata;    char key[10];    printf("sort List!\n");    SLInit(&SL);    printf("init SL List\n");    do{        printf("enter StdNo StdName, StdAge\n");        fflush(stdin);        scanf("%s%s%d", data.key,data.name, &data.age);        if(data.age)        {            if(!SLAdd(&SL, data))            {                break;            }        }        else        {            break;        }    }while(1);    printf("Show All\n");    SLAll(&SL);    fflush(stdin);    printf("Get Node: ");    scanf("%d", &i);    pdata = SLFindByNum(&SL, i);    if(pdata)    {        printf("number %d Node data: (%s,%s,%d)\n", i, pdata->key, pdata->name, pdata->age);    }    fflush(stdin);    printf("Get key: ");    scanf("%s", key);    i = SLFindByCont(&SL, key);    printf("%d\n", i);    pdata = SLFindByNum(&SL, i);    if(pdata)    {        printf("number %d Node data: (%s,%s,%d)\n", i, pdata->key, pdata->name, pdata->age);    }   // getch();    return 0;}

原创粉丝点击