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

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

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; 
	}
	//test
	void 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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值