反转链表,递归方法

用递归的方法翻转链表,思路是先翻转链表头结点以后的其他结点,最后将头节点放在链表的尾部。

若链表为空,则直接返空指针,若链表长度为1,则直接返回它。

#include <iostream>
using namespace std;

//定义链表结点
struct ListNode
{
      int       m_nKey;
      ListNode* m_pNext;
};

//创建链表
void CreateList(ListNode * &head)
{
	head = (ListNode *)malloc(sizeof(ListNode));
	head->m_nKey = 0;
	ListNode * temp = head;
	for(int i =1;i<10;i++)
	{
		ListNode *temp1 = (ListNode *)malloc(sizeof(ListNode));
		temp1->m_nKey = i;
		temp1->m_pNext = NULL;
		temp->m_pNext = temp1;
		temp = temp->m_pNext;
	}
}

//打印链表
void PrintList(ListNode * head)
{
	while(head)
	{
		cout<<head->m_nKey<<'\t';
		head = head->m_pNext;
	}
	cout<<endl;
}

//反转链表
ListNode* ReverseList(ListNode * pHead)
{
	if(pHead == NULL)
	{
		return NULL;
	}
	if(pHead->m_pNext == NULL)
	{
		return pHead;
	}
	ListNode * head = ReverseList(pHead->m_pNext);
	ListNode *temp = head;
	while(temp->m_pNext)
	{
		temp = temp->m_pNext;
	}
	temp->m_pNext = pHead;
	pHead->m_pNext = NULL;
	return head;

}

//测试
void main(){
	ListNode * head = NULL;
	CreateList(head);
	PrintList(head);
	head = ReverseList(head);
	cout<<endl;
	PrintList(head);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值