链表逆置递归

本文介绍了如何使用递归方法来逆置链表。首先创建了一个链表,然后通过递归函数`resever_list`实现了链表的逆置,最后打印了逆置后的链表节点值。

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

#include <iostream>
using namespace std;


typedef int ElemType;
typedef struct _Node
{
	ElemType data;
	struct _Node *next;
}Node;


Node* initNode()
{
	Node *ptr = (Node *)malloc(sizeof(struct _Node));
	if (ptr != NULL)
	{
		memset(ptr, 0, sizeof(Node));
		return ptr;
	}
	else 
		return NULL;
}

bool linkNode(Node* head, ElemType* start, ElemType* end, int num)
{
	if (head == NULL || end-start<0)
	{
		return false;
	}

	while(head->next != NULL)
	{
		head = head->next;
	}

	for(int i=0; i<num; ++i)
	{
		Node *tp = initNode();
		tp->data = *start;
		++start;
		head->next = tp;
		head = tp;
	}
	return true;
}

void Print(Node *head)
{
	if (head != NULL)
	{
		cout<<head->data<<" ";
		Print(head->next);
	}
}
void print_list(Node *head)
{
	if (head == NULL || head->next == NULL)
	{
		return ;
	}
	Print(head->next);
}

Node* re_list(Node *node, Node *next)
{
	if (node->next != NULL)
	{
		Node *head = re_list(node->next, next->next);
		next->next = node;
		node->next = NULL;
		return head;
	}
	else
	{
		return node;
	}
}

void resever_list(Node *head)//
{
	if (head == NULL || head->next == NULL)
	{
		return ;
	}
	Node *tmp = re_list(head->next, head->next->next);
	head->next = tmp;
}

int main()
{
	ElemType tp[] = {1,4,5,6,7,8,9};
	Node *head = initNode();
	linkNode(head, tp, tp+sizeof(tp),sizeof(tp)/sizeof(tp[0]));
	resever_list(head);
	print_list(head);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值