###非递归实现
//思路为将节点从前到后依次放到表头, 最少需要3个指针
ListNode * ReverseList(ListNode *list )
{
ListNode *head = NULL;
ListNode *current = list;
ListNode *next = NULL;
while (current != NULL) {
next = current->m_pNext;
current->m_pNext = head;
head = current;
current = next;
}
return head;
}
递归实现
ListNode * ReverseList2(ListNode * list)
{
//如果链表为空或者链表中只有一个元素
if(list == NULL || list->m_pNext == NULL)
return head;
ListNode * head = ReverseList2(list->m_pNext);//先反转后面的链表
list->m_pNext->m_pNext = list;//再将当前节点设置为其然来后面节点的后续节点
list->m_pNext = NULL;
return head;
}
###完整程序
#include <stdlib>
#include <iostream>
using namespace std;
//定义一个链表节点
typedef struct ListNode
{
int m_nKey;
struct ListNode * m_pNext;
}ListNode;
//插入一个新节点到链表中(放在链表头部)
void CreateList(ListNode * & head,int data)
{
//创建新节点
ListNode * p=(ListNode*)malloc(sizeof(ListNode));
p->m_nKey=data;
p->m_pNext=NULL;
if(head==NULL)
{
head=p;
return;
}
p->m_pNext=head;
head=p;
}
void printList(ListNode* head)
{
ListNode * p=head;
while(p!=NULL)
{
cout<<p->m_nKey<<" ";
p=p->m_pNext;
}
cout<<endl;
}
//思路为将节点从前到后依次放到表头, 最少需要3个指针
ListNode * ReverseList(ListNode *list )
{
ListNode *head = NULL;
ListNode *current = list;
ListNode *next = NULL;
while (current != NULL) {
next = current->m_pNext;
current->m_pNext = head;
head = current;
current = next;
}
return head;
}
//递归方式
ListNode * ReverseList2(ListNode * head)
{
//如果链表为空或者链表中只有一个元素
if(head==NULL || head->m_pNext==NULL)
return head;
ListNode * newhead=ReverseList2(head->m_pNext);//先反转后面的链表
head->m_pNext->m_pNext=head;//再将当前节点设置为其然来后面节点的后续节点
head->m_pNext=NULL;
return newhead;
}
int main()
{
ListNode * Head=NULL;
for(int i=0;i<10;i++)
CreateList(Head,i);
printList(Head);
Head=ReverseList2(Head);
printList(Head);
return 0;
}