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