/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
//递归版本
class Solution1 {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead== NULL||pHead->next == NULL)
return pHead;
ListNode * p = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = NULL;
return p;//只返回最后一个节点
}
};
//非递归版本
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead== NULL||pHead->next == NULL)
return pHead;
ListNode *pre = pHead;
ListNode * last = NULL;
ListNode * next = NULL;
while(pre != NULL)
{
next = pre->next;
pre->next = last;
last = pre;
pre = next;
}
return last;
}
};
剑指offer----逆转链表(递归+非递归方式)
最新推荐文章于 2022-07-30 11:20:23 发布