2021年12月计算机二级C++考前冲刺练习(一)
2021年12月计算机二级C++考前冲刺练习(一)
1[简答题]定义内联函数实现求三个实数中的最大值。
参考解析:
解:内联函数只适用于功能简单,代码短小而又被重复使用的函数。函数体中包含复杂结构控制语句,如switch、复杂if嵌套、while语句等,以及无法内联展开的递归函数,都不能定义为内联函数,即使定义,系统也将作为一般函数处理。
#include
inline max(int a,int b,int c){
if(a>b&&a>c) return a;
if(b>a&&b>c) return b;
if(c>a&&c>b) return c;
}
void main(){
cout<
}
2[简答题]设计一个单向链表类模板,节点数据域中数据从小到大排列,并设计插入、删除节点的成员函数。
参考解析:
#include
using namespace std;
templateclass List;
templateclass Node{
T info; //数据域
Node *link; //指针域
public:
Node(); //生成头结点的构造函数
Node(const T & data);//生成一般结点的构造函数
friend class List;
};
template Node::Node(){link=NULL;}
template Node::Node(const T & data){
info=data;
link=NULL;
}
//定义链表类
templateclass List{
Node *head; //链表头指针和尾指针
public:
List(); //构造函数,生成头结点(空链表)
~List(); //析构函数
void MakeEmpty(); //清空一个链表,只余表头结点
Node* Find(T data); //搜索数据域与data相同的结点,返回该结点的地址
void PrintList(); //打印链表的数据域
void InsertOrder(Node *p); //按升序生成链表
Node* CreatNode(T data); //创建一个结点(孤立结点)
Node* DeleteNode(Node* p); //删除指定结点
};
templateList::List(){
head=new Node(-9999);//头结点,最小的数据从小到大插入
}
templateList::~List(){
MakeEmpty();
delete head;
}
templatevoid List::MakeEmpty(){
Node *tempP;
while(head->link!=NULL){
tempP=head->link;
head->link=tempP->link; //把头结点后的第一个节点从链中脱离
delete tempP; //删除(释放)脱离下来的结点
}
}
template Node* List::Find(T data){
Node *tempP=head->link;
while(tempP!=NULL && tempP->info!=data) tempP=tempP->link;
return tempP; //搜索成功返回该结点地址,不成功返回NULL
}
templatevoid List::PrintList(){
Node* tempP=head->link;
while(tempP!=NULL){
cout
tempP=tempP->link;
}
cout<
}
templatevoid List::InsertOrder(Node *p){
Node *tempP=head,*tempQ=head; //tempQ指向tempP前面的一个节点
while(tempP!=NULL){
if(p->infoinfo)break; //找第一个比插入结点大的结点,由tempP指向
tempQ=tempP;
tempP=tempP->link;
}
p->link=tempP;
tempQ->link=p;
}
templateNode* List::CreatNode(T data){//建立新节点
Node*tempP=new Node(data);
return tempP;
}
templateNode* List::DeleteNode(Node* p){
Node* tempP=head->link,*tempQ=head,*tempC;
while(tempP!=NULL && tempP!=p){
tempQ=tempP;
tempP=tempP->link;
}
tempC=tempP;
tempQ->link=tempP->link;
return tempC;
}
int main(){
Node * P1;
List list1;
int a[10]={20,12,0,-5,9,-18,6,11,5,3},i,j;
for(i=0;i<10;i++){
P1=list1.CreatNode(a[i]);
list1.InsertOrder(P1);
}
list1.PrintList();
cout<<"请输入一个要求删除的整数"<
cin>>j;
P1=list1.Find(j);
if(P1!=NULL){
P1=list1.DeleteNode(P1);
delete P1;
list1.PrintList();
}
else cout<<"未找到"<
cout<<"请输入一个要求插入的整数"<
cin>>j;
P1=list1.CreatNode(j);
list1.InsertOrder(P1);
list1.PrintList();
list1.MakeEmpty();//清空list1
list1.PrintList();
return 0;
}
以上就是“2021年12月计算机二级C++考前冲刺练习(一)”及其相关内容,想及时获知2021年12月考试时间,大家可通过点击使用环球网校“ 免费预约短信提醒”,即可及时获得时间提醒。环球网校友情提示:为方便小伙伴们更好地备考,环球网校特地为大家准备了计算机二级复习资料,如有需要请点击文章下方“免费下载>>>2021年计算机二级考试真题及备考资料”下载学习。