输入一个链表,反转链表后,输出新链表的表头。
牛客网AC代码:
一、非递归
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr)
return nullptr;
ListNode* pre = nullptr,*cur = pHead;
while(cur != nullptr){
ListNode* last = cur->next;
cur->next = pre;
pre = cur;
cur = last;
}
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 == NULL)
return NULL;
return ReverseListCore(NULL,pHead);
}
ListNode* ReverseListCore(ListNode* pre,ListNode* cur){
ListNode *last = cur->next;
cur->next = pre;
if(last == NULL)//需要在cur指向pre后判断
return cur;
return ReverseListCore(cur,last);
}
};