方法一:在原链表上操作,设置前指针和当前指针,以及保存下一个结点地址的指针
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL)
{
return NULL;
}
else if(pHead->next==NULL)
{
return pHead;
}
ListNode*pre=NULL;
ListNode* p=pHead;
ListNode* temp=NULL;
while(p!=NULL)
{
temp=p->next;
p->next=pre;
pre=p;
p=temp;
}
return pre;
}
};
方法二:运用递归函数
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead->next==NULL||pHead==NULL)
{
return pHead;
}
ListNode*cur=ReverseList(pHead->next);
pHead->next->next=pHead;
pHead->next=NULL;
return cur;
}
};