用递归的方法翻转链表,思路是先翻转链表头结点以后的其他结点,最后将头节点放在链表的尾部。
若链表为空,则直接返空指针,若链表长度为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);
}