首页 > 代码库 > C++将链表反转的实现

C++将链表反转的实现

  有题目的需求是求将链表反转,例如1->2->3->4->5转变成5->4->3->2->1,经典的是可以有两种解决方法,递归方式和非递归方式,下面给出C++的这两周实现过程。

#include<iostream>using namespace std;const int N = 6;typedef int DataType;//定义数据类型typedef struct node{//创建链表node	DataType data;	struct node* next;}LinkedNode,*LinkList;LinkList CreateList(DataType a[N])//建表函数{	LinkedNode* ListHead = new LinkedNode();	ListHead->data= http://www.mamicode.com/a[0];"This is empty list"<<endl;	else		{			LinkedNode* p = ListHead;			while(p != NULL)			{				cout<<p->data<<" ";				p = p->next;			}			cout<<endl;		}}void RecReverseList(LinkedNode* pCur,LinkList& ListHead)//递归实现表的反转{	if( (NULL == pCur) || (NULL == pCur->next) )	{		ListHead = pCur;	}	else	{		LinkedNode* pNext = pCur->next;		RecReverseList(pNext,ListHead);		pNext->next = pCur;		pCur->next= NULL;			}}void UnRecReverseList(LinkList& ListHead)//非递归实现表的反转{	if(NULL == ListHead)		return ;	LinkedNode *pre,*cur,*nex;	pre = ListHead;	cur = pre->next;	while(cur)	{		nex = cur->next;		cur->next = pre;		pre = cur;		cur = nex;	}	ListHead->next= NULL;	ListHead = pre;	}int main(){	int a[N] = {1,2,3,4,5,6};	LinkedNode* list = CreateList(a);	PrintList(list);	LinkedNode* pTemp = list;	RecReverseList(pTemp,list);	PrintList(list);	UnRecReverseList(list);	PrintList(list);	return 0;}

  运行结果:技术分享

C++将链表反转的实现