反转链表的循环方式和递归方式

出自《剑指Offer》第16题。

题目:定义一个函数,输入一个链表的头结点,反转该链表并输出翻转后的链表的头结点。

链表的结点定义:

struct ListNode
{
int m_nKey;
ListNode *m_pNext;

};


反转的过程主要是先把pNode所指向的结点用临时指针保存一下,然后你转pNode,使得pNode指向它的前一个结点。最后再更新pNode,pPre。

循环法:

ListNode * ReverseList(ListNode *pHead)
{
	ListNode *pReverseHead=NULL;
	ListNode *pNode=pHead;
	ListNode *pPrev=NULL;
	while(pNode!=NULL)
	{
		ListNode *pNext=pNode->m_pNext;
		if(pNext==NULL)
			pReverseHead=pNode;
		pNode->m_pNext=pPrev;
		pPrev=pNode;
		pNode=pNext;
	}
	return pReverseHead;
}

递归法:

ListNode *reverse(ListNode *pPrev,ListNode *pNode)
{
	if(pNode==NULL)
		return pPrev;
	ListNode *pNext=pNode->m_pNext;
	pNode->m_pNext=pPrev;
	pPrev=pNode;
	pNode=pNext;
	return reverse(pPrev,pNode);
}
ListNode * ReverseList_recursion(ListNode *pHead)
{
	ListNode *pNode=pHead;
	ListNode *pPrev=NULL;
	return reverse(pPrev,pNode);
}
定义链表的结构、初始化链表、打印链表中数据。

#include<iostream>
using namespace std;
struct ListNode
{
	int m_nKey;
	ListNode *m_pNext;
};
ListNode * initialList(int arr[],int len)
{
	ListNode *head=new ListNode;
	ListNode *p=head;
	ListNode * node=NULL;
	for(int ii=0;ii<len;ii++)
	{
		node=new ListNode;
		node->m_nKey=arr[ii];
		p->m_pNext=node;
		p=node;
	}
	p->m_pNext=NULL;
	ListNode *temp=head;
	head=head->m_pNext;
	delete temp;
	return head;
}
void printList(ListNode *head)
{
	if(head==NULL)
		cout<<"Empty List!"<<endl;
	else
	{
		while(head!=NULL)
		{
			cout<<head->m_nKey<<"\t";
			head=head->m_pNext;
		}
		cout<<endl;
	}
}

清空链表:

void clearList(ListNode * &head)
{
	if(head==NULL)
		return;
	while(head!=NULL)
	{
		ListNode * temp=head;
		head=head->m_pNext;
		delete temp;
		temp=NULL;
	}
	
}

测试程序:

int main()
{
	int arr[]={1,2,3,4,5,6,7,8,9,10};
	int len=sizeof(arr)/sizeof(arr[0]);

	cout<<"循环法反转链表:"<<endl;
	
	ListNode *head=initialList(arr,len);
	cout<<"反转前:"<<endl;
	printList(head);
	head=ReverseList(head);
	cout<<"反转后:"<<endl;
	printList(head);
	clearList(head);//清空链表

	cout<<"递归法反转链表"<<endl;
	head=initialList(arr,len);
	cout<<"反转前:"<<endl;
	printList(head);
	head=ReverseList_recursion(head);//递归形式
	cout<<"反转后:"<<endl;
	printList(head);
	clearList(head);

	cout<<"循环法输入为空链表时"<<endl;
	head=initialList(arr,0);
	cout<<"反转前:"<<endl;
	printList(head);
	head=ReverseList(head);
	cout<<"反转后:"<<endl;
	printList(head);
	clearList(head);

	cout<<"递归法输入为空链表时"<<endl;
	head=initialList(arr,0);
	cout<<"反转前:"<<endl;
	printList(head);
	head=ReverseList(head);
	cout<<"反转后:"<<endl;
	printList(head);


	return 0;
}

测试结果:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值