递归方法反转链表

本文介绍了一种使用递归方法实现单链表反转的C++程序。通过定义节点结构体和相关函数,实现了链表的创建、反转及打印功能。该程序首先创建一个单链表,然后使用递归算法进行链表的反转,并最后输出反转后的链表。

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



<span style="font-size:18px;">#include <iostream>
#include <time.h>
#include <string>
using namespace std;

//单链表反转

struct node
{
	int data;
	node *next;
};

void Create(node * &head)
{
	int data;
	cin>>data;
	node *p1,*p2;
	while(data!=-1)
	{
		if(head==NULL)
		{
			head=new node;
			head->data=data;
			head->next=NULL;
			p1=head;
		}
		else
		{
			p2=new node;
			p2->data=data;
			p1->next=p2;
			p1=p2;
			p1->next=NULL;

		}
		cin>>data;
	}
}
void Print(node *head)
{
	while(head!=NULL)
	{
		cout<<head->data<<' ';
		head=head->next;
		
	}
}

node *Reverse(node *p,node *&head)
{
	if(p->next==NULL)
	{
		head->next=NULL;
		head=p;
		return p;
	}
	else
	{
		node *tmp=Reverse(p->next,head);
		tmp->next=p;
		return p;
	}
}
void main()
{
	node *head=NULL;
	Create(head);
	Reverse(head,head);
	Print(head);

	
}
</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值