单链表反转

#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");
}


 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值