C++primer plus第六版课后编程题答案10.8

来源:互联网 发布:联想固态硬盘优化软件 编辑:程序博客网 时间:2024/06/05 02:53

因为不太会最后一个要求,所以我这里最后一个要求没有实现,知道怎么实现的告诉我下

List.h

#ifndef LIST_H_#define LIST_H_template <class T>struct Node{T num;struct Node *next;};template <class T>class List{static const int MAX=10;private://T t[MAX];//int top;Node<T> *front;Node<T> *rear;int qsize;Node<T> *now;public://List<T>(int m);List();~List();//构造函数有new ,必须显示析构void add(const T &t);bool isEmpty()const;bool isFull()const;//void set(const T &t)const;void visit(){Node<T> *p=front;Node<T> *q=front->next;while(q!=rear){cout<<"p->num="<<p->num<<"  "<<endl;cout<<"q->num="<<q->num<<"  "<<endl;//cout<<"front="<<front->num<<endl;//cout<<"rear="<<rear->num<<endl;p=q;//q=q->next;//后移//if(q==rear)//仔细调试一番,就会知道为什么//break;}cout<<"\nshow end!"<<endl;};void showNow(){cout<<"\nnow is "<<now->num<<endl; }void showRear(){cout<<"\nRear is "<<rear->num<<endl; }//testvoid test(){cout<<"Just test!"<<endl;}};#endif

List.cpp

#include <iostream>#include "List.h"using  std::cout;using std::cin;using std::endl;template <class T>List<T>::List()//模板类的定义必须有模板参数,不能写出List::List!!{front=rear=nullptr;qsize=0;}template <class T>List<T>::~List()//模板类的定义必须有模板参数,不能写出List::List!!{delete front;//释放指向首指针的内容}template <class T>//必须写出模板类,否则T无效void List<T>::add(const T &t) {if(isEmpty()){Node<T> *n=new Node<T>;front=n;n->num=t;n->next=nullptr;qsize++;now=n;//令now指向当前节点rear=n->next;}else if(isFull()){cout<<"List is full"<<endl;}else{Node<T> *n=new Node<T>;n->num=t;now->next=n;n->next=nullptr;qsize++;now=n;//令now指向当前节点rear=n->next;}}template <class T>bool List<T>::isEmpty()const{//front=nullptr;//不是不能改变里面的数据么?//qsize=100;编译无报错,但是运行阶段会报错//cout<<"const is not work! "<<qsize<<endl;return front==nullptr;}template <class T>bool List<T>::isFull()const{return qsize==MAX;}

main108.cpp

#include <iostream>#include "List.cpp"//不要写出List.h,不然会出现外部链接错误using  std::cout;using std::cin;using std::endl;void main108(){const int ar1[5]={1,2,3,4,5};double ar2[12]={1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.1,11.2};List<int> arr1;List<double> arr2;for(int i=0;i<5;i++){arr1.add(ar1[i]);//arr1.showNow();//arr1.showRear();}for(int i=0;i<11;i++){arr2.add(ar2[i]);arr2.showNow();}//arr1.add(10);arr1.visit();//arr1.test();cin.get();}


0 0
原创粉丝点击