#C++PrimerPlus# Chapter10_Exersice8_v1.0

本文介绍了一个简单的链表类实现过程,使用C++编程语言。该链表类包含基本的操作如添加元素、检查列表状态等,并提供了完整的源代码及运行示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意似乎有点难理解,题面提及的链表似乎之前也没介绍过。

从简单做起,定义一个类List:

私有部分:元素数为5的bool类型的数组,false代表列表空,true代表列表满。

       一个计数器,int变量,记录多少个列表项为满。

公有部分:初始化函数,初始空列表。

     添加修改某列表项的函数,以列表项编号为参数。

     访问某编号列表项,返回它的值。(内联)

     检验列表是否为空或满的函数。

     显示整个列表的函数。

程序清单如下:


 

// list.h
#ifndef LIST_H_
#define LIST_H_

// 此处修改列表的数据类型
typedef bool Item;

class List
{
private:
    enum {SIZE = 5};
    Item lists[SIZE];
    int count;
public:
    List();
    void setList(int num);
    const Item& visitList(int num) const {return lists[num-1];}
    bool ifEmpty(void) const;
    bool ifFull(void) const;
    void showLists(void) const;
};

#endif


// list.cpp
#include <iostream>
#include "list.h"

List::List()
{
    for (int i = 0; i < SIZE; i++)
        lists[i] = false;
    count = 0;
}

// 此处修改列表对应数据类型的输入方法
void List::setList(int num)
{
    using std::cout;
    using std::cin;
    cout << "请输入您想要添加进列表项" << num << "的值:";
    if (lists[num-1] != 0)
        count--;
    while (!(cin >> lists[num-1]))
    {
        cin.clear();
        while (cin.get() != '\n')
            continue;
        cout << "输入错误,请重新输入。\n";
    }
    while (cin.get() != '\n')
        continue;
    if (lists[num-1] != 0)
        count++;
}

bool List::ifEmpty(void) const
{
    return count == 0;
}

bool List::ifFull(void) const
{
    return count == 5;
}

// 此处修改列表对应数据类型的输出方法
void List::showLists(void) const
{
    std::cout << "列表状态为:";
    for (int i = 0; i < SIZE; i++)
        std::cout << lists[i];
    std::cout << std::endl;

}


 // uselist.cpp
#include <iostream>
#include "list.h"

int main()
{
    using std::cout;
    using std::cin;
    List newList;
    newList.showLists();
    int listNum;
    cout << "请输入您要修改的列表项编号(1-5),其他任意值退出程序:";
    while (cin >> listNum)
    {
        while (cin.get() != '\n')
            continue;
        newList.setList(listNum);
        newList.showLists();
        if (newList.ifFull())
            cout << "列表已满。\n";
        if (newList.ifEmpty())
            cout << "列表已清空。\n";
        cout << "请输入您要修改的列表项编号(1-5),其他任意值退出程序:";
    }
 
    return 0;
}


结束。

转载于:https://www.cnblogs.com/zhuangdong/archive/2013/04/27/3044141.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值