反向输出链表

本文介绍了一个简单的链表反转算法,并提供了完整的C++实现代码。通过该算法,可以将单向链表中的节点顺序进行反转。文章还展示了如何创建链表及打印链表中的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码: #include <iostream>
#include <vector>
#include <iterator>
#include <cassert>
#include<algorithm>//copy using namespace std;
const int n=2;
struct node
{
int i;
node *next;
};
node *Reverse(node *head)
{
//判断链表是否为空
assert(head != NULL && " function Reverse : list is null!");
node *temp=head->next;
//链表只有一个元素情况
if(temp == NULL ) return head;
//链表翻转前head-->temp-->tail,翻转后tail-->temp-->head
head->next=NULL;
node *tail=temp->next;
while(tail != NULL)
{
temp->next=head;
head=temp;
temp=tail;
tail=tail->next;
}
temp->next=head;
//返回翻转后的链表头指针
return temp;
}
void Print(node *head)
{
while(head != NULL)
{
cout<<head->i<<" ";
head=head->next;
}
cout<<endl;
}
int main()
{
node *head=NULL,*tail=NULL,*temp=NULL;
head= new node;
head->i=1;head->next=NULL;
tail=head;
for(int i=2;i<=n;++i)
{
temp =new node;
temp->i=i;temp->next=NULL;
tail->next=temp;
tail=temp;
}
Print(head);
cout<<"------------"<<endl;
head=Reverse(head);
Print(head);

return 0;  

}

转载于:https://my.oschina.net/u/2312175/blog/679681

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值