您的位置:首页 > 其它

【100题】反转链表(递归实现)

2012-07-25 22:52 337 查看
//
#include <iostream>
using namespace std;

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

//创建链表
void createList(ListNode *&Head)
{
	 int num = 0;
	 int flag = 0;
	 ListNode *p = NULL;
	 cin >> num;
	 
	 Head = (ListNode *)malloc(sizeof(ListNode));
	 while(num != 0)
	 {
		  if(flag == 0)
		  {  
			   Head->data = num;
			   Head->next = NULL;
			   flag = 1;
			   p = Head;
		  }
		  else
		  {
			   ListNode *cur = (ListNode *)malloc(sizeof(ListNode));
			   cur->data = num;
			   cur->next = NULL;
			  
			   p->next = cur;
			   p = cur;
		  } 
		  cin >> num;
	 }
}

//打印链表
void printList(ListNode *Head)
{
	 if(Head == NULL)
	 {
		  cout << "Head empty"<<endl;
		  return ;
	 }
	 ListNode *p = Head;
	 while(p != NULL)
	 {
		  cout << p->data <<" ";
		  p = p->next;
	 }
}

//递归反转链表
ListNode* reverseLinkList_recursion(ListNode* pNode,ListNode*& head)
{
     if(pNode == NULL || pNode->next == NULL)
    {
          head->next = NULL;    //把反转后的最后一个节点的next域置为NULL
          head = pNode;
          return pNode;
     }
     ListNode* tmpNode = reverseLinkList_recursion(pNode->next,head);//返回原链表中pNode的下一个节点
     tmpNode->next = pNode;
     return pNode;
}

void main()
{
	 ListNode *List = NULL;
	 cout << "创建链表:";
	 createList(List);
	 cout << "链表元素:";
	 printList(List);
	 reverseLinkList_recursion(List,List);
	 cout <<endl<< "倒序后:";
	 printList(List);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: