出自《剑指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;
}
测试结果: