#include <iostream>
using namespace std;
struct node{
int num;
node* next;
};
class list{
public:
list();
void print();
void turnover();
private:
node* p;
node* q;
node* head;
};
void list::turnover(){
node* p1;
q=head;
if(q->next!=NULL)
p=q->next;
else{
cout<<"链表就一个元素"<<endl;
return;
}
while(p->next!=NULL){
p1=p->next;
p->next=q;
q=p;
p=p1;
}
p->next=q;
head->next=NULL;
head=p;
}
list::list(){
head=new node;
head->num=1;
head->next=NULL;
p=new node;
p->num=2;
head->next=p;
p->next=NULL;
for(int i=3;i<=5;i++){
q=p;
p=new node;
p->num=i;
q->next=p;
p->next=NULL;
}
}
void list::print(){
p=head;
while(p!=NULL){
cout<<p->num<<endl;
p=p->next;
}
}
void main()
{
list test;
test.turnover();
test.print();
getchar();
}
程序2:
//程序完成单链表的反转
#include <iostream>
using namespace std;
struct node{
int num;
node* next;
};
class list{
public:
void create();
void turnover();
private:
node* head;
};
void list::turnover(){
node *p;
if(NULL==head)
cout<<"链表为空"<<endl;
else if(NULL==head->next)
cout<<"只有一个头节点"<<endl;
else if(NULL==head->next->next){
cout<<"只有两个节点"<<endl;
p=head;
head=head->next;
head->next=p;
p->next=NULL;
}
else{
node *p0,*p1;//这两个指针用于记录p的前后位置
p0=head;
p=head->next;
p1=p->next;
p0->next=NULL;
while(p1){
p->next=p0;
p0=p;
p=p1;
p1=p1->next;
}
p->next=p0;
head=p;
}
cout<<"反转操作已完成,输出:"<<endl;
p=head;
while(p){
cout<<p->num<<" ";
p=p->next;
}
}
void list::create(){
int i;
node *p,*q;
cout<<"请输入您要输入的数字,按任意非数字键退出(空格、回车除外)"<<endl;
cin>>i;
if(cin.fail()){
cout<<"您的输入有误"<<endl;
cout<<"按任意键结束"<<endl;
getchar();
exit(-1);
}
head=new node;
head->num=i;
head->next=NULL;
p=head;
while(1){
cout<<"请输入您要输入的数字:"<<endl;
cin>>i;
if(cin.fail())
break;
q=p;
p=new node;
p->num=i;
p->next=NULL;
q->next=p;
}
}
void main()
{
list test;
test.create();
cout<<endl<<endl<<"输入完毕"<<endl<<endl;
test.turnover();
system("pause");
}