//
#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);
}
【100题】反转链表(递归实现)
最新推荐文章于 2023-12-03 18:23:51 发布