📄 headerlist.cpp
字号:
#include<iostream.h>
class HeaderList;
class Node
{
private:
int element;
Node*link;
friend class HeaderList;
};
class HeaderList
{
public:
HeaderList()
{
first=new Node;
first->link=NULL;
n=0;
}
~HeaderList();
bool Insert(int i,int x);
void Output(ostream &out)const;
void Invert();
void PrintMaxMin();
private:
Node*first;
int n;
};
HeaderList::~HeaderList()
{
Node*p;
while(first)
{
p=first->link;
delete first;
first=p;
}
}
bool HeaderList::Insert(int i,int x)
{
if(i<-1||i>n-1)
{
cout<<"out of bounds"<<endl;
return false;
}
Node*q=new Node;
q->element=x;
Node*p=first;
for(int j=0;j<=i;j++)
p=p->link;
q->link=p->link;
p->link=q;
n++;
return true;
}
void HeaderList::Output(ostream &out)const
{
out<<"单链表中的元素:"<<endl;
Node*p=first->link;
while(p)
{
out<<p->element<<" ";
p=p->link;
}
out<<endl;
}
void HeaderList::Invert()
{
Node*p,*q;
p=first->link;
first->link=NULL;
while(p)
{
q=p->link;
p->link=first->link;
first->link=p;
p=q;
}
}
void HeaderList::PrintMaxMin()
{
if(n==0)
{
cout<<"单链表为空"<<endl;
return;
}
Node*p=first->link;
int max,min;
max=min=p->element;
while(p)
{
if(p->element>max)max=p->element;
else
{
if(p->element<min)min=p->element;
}
p=p->link;
}
cout<<"单链表中最大值是"<<max<<endl;
cout<<"单链表中最小值是"<<min<<endl;
}
void CreateHeaderList(HeaderList&h1,int n)
{
int temp;
cout<<"请输入"<<n<<"个整数"<<endl;
for(int i=0;i<n;++i)
{
cin>>temp;
h1.Insert(i-1,temp);
}
}
void main()
{
HeaderList h1;
int num;
cout<<"请输入你要输入元素的个数:"<<endl;
cin>>num;
CreateHeaderList(h1,num);
h1.Output(cout);
h1.PrintMaxMin();
cout<<"单链表所有元素逆置"<<endl;
h1.Invert();
h1.Output(cout);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -