c++链表演示

#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
#define MAXLEN 100
typedef struct
{
    char key[10];
    char name[20];
    int age;
}DATA;
typedef struct
{
    DATA ListData[MAXLEN + 1];
    int ListLen;
}SLType;
void SLInit(SLType*SL)//初始化顺序表
{
    SL->ListLen = 0;
}
int SLLength(SLType*SL)//返回顺序表的元素数量
{
    return(SL->ListLen);
}
int SLInsert(SLType*SL, int n, DATA data)//只在表间插入
{
    int i;
    if (SL->ListLen >= MAXLEN)
    {
        cout << "顺序表已满,不能插入结点!\n";
        return 0;
    }
    if (n<1 || n>SL->ListLen - 1)//插入结点序号不正确
    {
        cout<<"插入结点的序号错误"; 
        return 0; 
    }
    for (i = SL->ListLen; i >= n; i--)
    {
        SL->ListData[i + 1] = SL->ListData[i];
    }
    SL->ListData[n] = data;
    SL->ListLen++;
    return 1;//成功插入返回1
}
int SLAdd(SLType*SL, DATA data)
{
    if (SL->ListLen >= MAXLEN)
    {
        cout << "顺序已满,不能再添加结点了" << endl;
        return 0;
    }
    SL->ListData[++SL->ListLen] = data;
    return 1;
}
int SLDelete(SLType* SL, int n)
{
    int i;
    if (n<1 || n>SL->ListLen + 1)
    {
        cout << "删除结点序号错误,不能删除"; 
        return 0;
    }
    for (i = n; i < SL->ListLen; i++)
    {
        SL->ListData[i] = SL->ListData[i + 1];
    }
    SL->ListLen--;
    return 1;
}
DATA*SLFindByNum(SLType*SL, int n)
{
    if (n<1 || n>SL->ListLen + 1)
    {
        cout << "结点序号错误,不能返回结点";
        return NULL;
    }
    return &(SL->ListData[n]);
}
int 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; 
}
int SLALL(SLType*SL)
{
    int i;
    for (i = 1; i <=SL->ListLen; i++)
    {
        cout << SL->ListData[i].key << SL->ListData[i].name << SL->ListData[i].age << endl;
    }
    return 0;
}
int main()
{
    int i;
    SLType SL;
    DATA data;
    DATA *pdata;
    char key[10];
    cout << "顺序操作表演示" << endl;
    SLInit(&SL);
    cout << "链表初始化完成" << endl;
    do
    {
        cout << "输入添加的结点(学号 姓名 年龄):" << endl;
        fflush(stdin);//清空输入缓冲区
        cin>>data.key>>data.name>>data.age;
        if (data.age)//若年龄不为0
        {
            if (!SLAdd(&SL, data))
            {
                break;
        }
    }
        else
        {
            break;
        }
    } while (1);
    cout << "顺序表中的结点顺序为:" << endl;
    SLALL(&SL);//显示所有的结点数据
    fflush(stdin);
    cout << "要取出结点的序号:" << endl;
    cin >> i;
    pdata = SLFindByNum(&SL, i);
    if (pdata)
    {
        cout << i << pdata->key << pdata->name << pdata->age << endl;
    }
    fflush(stdin);
    cout << "要查找结点的关键字" << endl;
    cin >> key;
    i = SLFindByCont(&SL, key);
    pdata = SLFindByNum(&SL, i);
    if (pdata)
    {
        cout << i << pdata->key << pdata->name << pdata->age << endl;
    }
    getch();
    return 0;
}

 

posted @ 2019-03-13 21:22  Maggieisxin  阅读(196)  评论(0)    收藏  举报