实验目的:
通彻代码原理,并加以灵活应用,对书本的知识进行创新以及改良。
实验代码:
头文件:
#include <iostream>
using namespace std;
class student{
public:
student(){cout<<"please input data"<<endl;cin>>name; cin>>number;}
void print(){cout<<"学生名字:"<<name<<endl; cout<<"number:"<<number<<endl;}
private:
char name[10];
int number;
};
class List{
public:
List(){first=new Node;first->next=NULL;}
List(int n);
int length();
void Get(int i);
void insert(int i,float x);
float Delete(int i);
void printList();
private:
class Node
{
public:
student *data;
Node *next;
Node(){
next=NULL;}
};
Node *first;
int count;
};
源文件:
#include <iostream>
#include "tou.h"
using namespace std;
void List::printList()
{
Node *p;
p=first->next;
while(p!=NULL)
{
p->data->print(); cout<<",";
p=p->next;
}
}
int List::length(){
Node *p;
p=first->next;
count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
return count;}
void List::Get(int i){
Node *p;
p=first->next; count=1;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL)throw"位置";
else cout<<endl; p->data->print(); cout<<endl;
}
List ::List(int n){
first=new Node;Node *s=new Node; Node *r=new Node;
for(int i=0;i<n;i++){
student *student1=new student();
s->data=student1;
r=first;
r->next=s;
r=s;
r->next=NULL;
}
}
void main(){
int n;
n=1;
List x(n);
x.printList();
system("pause");
}
实验结果:
总结:
由于之前实验中数据类型单一,在实践应用中无法应用,老师提议讲数据类型复杂化,于是对代码进行修改改良,将结点作为链表的内部类,另外创建一个储存信息的student类,于结点类中创建studnet类对象,因此可以将数据类型复杂化。