您的位置:首页 > 编程语言 > C语言/C++

构造双向链表根据访问频度动态调整位置_C++实现

2011-09-13 19:53 579 查看
遇到了一点小问题

在使用Ctrl+Z结束输入时主函数的cin就不能用了

百思不得其解

后来上论坛问了下

才知道原来是cin的异常状态没有清除

又长了点见识

"head.h"

#include<iostream>
using namespace std;

class NODE
{
public:
NODE();
NODE *pre,*next;
int num,freq;
};

NODE::NODE()
{
pre=next=NULL;
num=freq=0;
}

class DATA
{
public:
DATA();
void Constructor();
void Locate();
void Print();
private:
void Adjust();
NODE *head,*p,*pre;
};

DATA::DATA()
{
head=p=pre=NULL;
}

void DATA::Constructor()
{
cout<<"Constructor Called !"<<endl<<endl;
cout<<"Please Input Data :"<<endl<<endl;
int num;
bool hasinput=false;
while(cin>>num)
{
if(hasinput==false)
{
head=new NODE;
head->num=num;
pre=p=head;
hasinput=true;
}
else
{
p->next=new NODE;
p=p->next;
p->num=num;
p->pre=pre;
pre=p;
}
}
if(!hasinput)
{
cout<<"No Data Has Been Input !"<<endl<<endl;
}
else
{
head->pre=p;
p->next=head;
}
}

/*
void DATA::Constructor()
{
cout<<"Constructor Called !"<<endl<<endl;
int numlen,num;
cout<<"How Many Number Do You Want To Enter ?"<<endl<<endl;
cin>>numlen;
if(numlen==0)
return;
cout<<"Please Input Data !"<<endl<<endl;
cin>>num;
head=new NODE;
head->num=num;
pre=p=head;
numlen--;
while(numlen--)
{
p->next=new NODE;
p=p->next;
cin>>num;
p->num=num;
p->pre=pre;
pre=p;
}
p->next=head;
head->pre=p;
}
*/
void DATA::Locate()
{
cout<<"Locate Called !"<<endl<<endl;
int goal;
if(head==NULL)
{
cout<<"No Data !"<<endl<<endl;
return;
}
else
{
cout<<"Which Number Do You Want To Locate"<<endl<<endl;
cin>>goal;
if(head->num==goal)
{
cout<<"Find It !"<<endl;
head->freq++;
cout<<head->num<<" : "<<head->freq<<endl;
}
else
{
p=head->next;
while(p!=head)
{
if(p->num==goal)
{
cout<<"Find It !"<<endl;
p->freq++;
cout<<p->num<<" : "<<p->freq<<endl;
Adjust();
return;
}
else
p=p->next;
}
cout<<"Not Found !"<<endl<<endl;
}
}
}

void DATA::Adjust()
{
pre=p->pre;
while(p!=head)
{
if(p->freq>pre->freq)
{
int temp;
temp=p->num;
p->num=pre->num;
pre->num=temp;
temp=p->freq;
p->freq=pre->freq;
pre->freq=temp;
}
p=pre;
pre=pre->pre;
}
}

void DATA::Print()
{
cout<<"Print Called !"<<endl<<endl;
if(head==NULL)
{
cout<<"No Data !"<<endl<<endl;
return;
}
cout<<head->num<<" : "<<head->freq<<endl;
p=head->next;
while(p!=head)
{
cout<<p->num<<" : "<<p->freq<<endl;
p=p->next;
}
cout<<endl;
}


"main.cpp"

#include<iostream>
#include"head.h"
#include<string>
using namespace std;

int main()
{
DATA data;
char choice;
data.Constructor();
cin.clear();
//Ctrl + Z模拟了一个已经到了文件尾,这时候再使用 while(cin>>ch)是效果是false的,所以第二段失效了cin.clear()用以清除错误状态
while(1)
{
cout<<"Your Choice , Please ?"<<endl<<endl
<<"1 . Locate"<<endl
<<"2 . Print"<<endl
<<"3 . Quit"<<endl<<endl;
cin>>choice;
switch(choice)
{
case '1':
data.Locate();
break;
case '2':
data.Print();
break;
case '3':
return 0;
default:
cout<<"Input Error ! Please Enter Your Choice As Shown Above !"<<endl;
break;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: