用双向链表实现超长整数加减法

学校数据结构的课程实验之一。
用到的数据结构:双向链表
主要功能:对由用户输入的两个任意长的整数进行加减运算
主函数:

int main()
{

    short num;//临时数据段
    char optr;//运算符
    char ch;//临时字符接收
    char choice = 'y';

    while (choice == 'y')
    {
        List<List_entry> *list1 = new List<List_entry>();
        List<List_entry> *list2 = new List<List_entry>();
        cout << "请输入第一个运算数,每三位用逗号分隔,以#结束:" << endl;
        cin >> ch;
        if (ch == '-') list1->sign = 1;
        else cin.putback(ch);
        while (ch != '#')
        {
            cin >> num;//读入一段(3位)整数
            list1->insert_tail(num);//构建第一个运算数的链表
            cin >> ch;//吸收用于分隔的逗号
        }

        cout << "第一个运算数已保存,请输入第二个运算数:" << endl;
        cin >> ch;
        if (ch == '-') list2->sign = 1;
        else cin.putback(ch);
        while (ch != '#')
        {
            cin >> num;
            list2->insert_tail(num);
            cin >> ch;
        }

        cout << "第二个运算数已保存,请输入运算符(+或-):" << endl;
        cin >> optr;

        cout << "运算表达式为:" << endl;
         list1->print();cout << endl;
        cout << optr;
        list2->print();
        cout << endl;

        List<List_entry>* result = operate(list1, list2, optr);
        cout << "运算结果为:" << endl;
        result->print();
        cout << endl;
        delete result, list1, list2;
        cout << "是否继续?[y/n]";
        cin >> choice;
    }

}

链表结点定义

template<class Node_entry>//结点定义
struct Node
{
    //数据成员
    Node_entry entry;
    Node<Node_entry> *back;
    Node<Node_entry> *next;

    //构造函数
    Node(){}
    Node(Node_entry new_entry, 
        Node<Node_entry> *new_back=NULL, Node<Node_entry> *new_next=NULL)
    :entry(new_entry), back(new_back), next(new_next){}
};

双链表的定义

template<class List_entry>
class List
{
public:
    unsigned int count;//结点个数
    Node<List_entry> *head, *tail;//链表头、尾结点
    short sign;//符号

    List()//构造函数
    {
        count=0;
        head=tail=NULL;
        sign=0;
    }
    Error_code insert_tail(const List_entry x)//插在末尾
    {
        Node<List_entry> *new_node=new Node<List_entry>(x);
        if(head==NULL) head=tail=new_node;//第一个结点
        else
        {
            tail->next = new_node;
            new_node->back = tail;
            tail =
  • 4
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值