单链表反转

//单链表反转
#include<iostream>
using namespace std;
typedef int elemType;


//定义结点
struct Node
{
elemType data;
Node* next;
};


//创建链表----无头结点
Node* creatList(int n)
{
Node* head=new Node;
Node* p=head;
int i;
for(i=1;i<n;i++)
{
p->data=i;
p->next=new Node;
p=p->next;
}
p->data=i;
p->next=NULL;
return head;
}


//单链表的整表创建(尾插法),带头节点易后续操作
/*Node* creatList(int n)
{
Node* L=new Node; //头结点
Node *p,*r;
//srand(time(0));  //初始化随机种子
r=L;   //r为指向表尾的结点
for(int i=1;i<=n;i++)
{
p=new Node; //生成新结点
p->data=i;  //=rand()%100+1;
r->next=p; //将表尾结点的指针指向新结点
r=p;   //新结点为表尾
}
r->next=NULL;  //表示当前链表结束
return L;
}*/


//显示链表各结点值
void showList(Node* head)
{
Node* p=head;
while(p)
{
cout<<p->data;
p=p->next;
cout <<'\t';
}
cout << endl;
}


//反转链表,方法一:让原链表中的指针箭头反向!
Node* list_turn(Node* head)
{
if(head==0||head->next==0) return head;//
Node *pre=NULL; //pre为辅助指针
Node *cur=head;     //cur指向当前结点
Node *pnext=NULL;   //pnext也为辅助指针
while(cur->next)
{
pnext=cur->next; //将当前结点下一结点(地址)保存下来,为下一次遍历准备(cur=pnext)
cur->next=pre;  //当前节点里面的next指针反转向前指


pre=cur; //将当前节点保存起来作为下一次的前结点
cur=pnext; //cur指向下一个结点(第一步保存的那个结点)

/*pnext=pre;
pre=cur;
cur=cur->next;
pre->next=pnext;*/
}
cur->next=pre;
return cur;
}


int main()
{
int n;
cout <<"输入需要创建链表的结点数n:"<<endl;
cin >>n;
Node* head=creatList(n);
cout <<"创建的新链表各结点的值:"<<endl;
showList(head);
Node *result=list_turn(head);
cout <<"反转后的链表各结点的值:"<<endl;
showList(result);
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值