单链表
#include<iostream>
#include<fstream>
#define N 100
using namespace std;
struct student{
char num;
char name;
struct student *next;
};
class Linklist{
struct student first;//头结点
public:
Linklist();
Linklist(student a[],int n);
int Length();
~Linklist();
void PrintList();
};
Linklist::Linklist(){
first.next=NULL;
}
int Linklist::Length(){
int n=0;
struct student *p;
p=first.next;
while(p){
n++;
p=p->next;
}
cout<<n<<endl;
}
Linklist::Linklist(student a[],int n){
first.next=NULL;
for(int i=0;i<n;i++){
struct student *p=new student;
p->num=a[i].num;
p->name=a[i].name;
p->next=first.next;
first.next=p;
}//头插法
}
Linklist::~Linklist(){
struct student *p;
while(first.next){
p=first.next;
first.next=p->next;
delete p;
}
}
void Linklist::PrintList(){
struct student *p;//
p=first.next;//
while(p){
cout<<p->num<<' '<<p->name<<endl;
p=p->next;
}
}
int main(){
// struct student a[N]={
// {1,'a'},
// {2,'b'},
// {3,'c'}//不能写成 "c"
// };//结构体数
// int n=3;
struct student a[N];
int n=3;
ifstream infile("1.txt",ios::in);
if(!infile){
cerr<<"open error!";
exit(1);
}
// while(infile){
// for(int i=0;i<n;i++){
// infile>>a[i].num>>a[i].name;
// n++;
// }
// }//错
for(int i=0;i<n;i++)
infile>>a[i].num>>a[i].name;
infile.close();
Linklist x(a,n);
x.PrintList();
x.Length();
return 0;
}
疑问:如何在计算文件中数据的个数?