帮你拿下反转链表 | LeetCode:206.反转链表 | 双指针法 | 递归法_哔哩哔哩_bilibili
虚拟头节点的做法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
vector<int>v;
while(head)
{
v.push_back(head->val);
head=head->next;
}
reverse(v.begin(),v.end());
ListNode* dummyNode=new ListNode(-1);
ListNode* res=dummyNode;
for(auto& it:v)
{
dummyNode->next=new ListNode(it);
dummyNode=dummyNode->next;
}
return res->next;
}
};
双指针写法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL)return head;
ListNode* prev=NULL;
ListNode* cur=head;
while(cur)
{
ListNode* temp=cur->next;
cur->next=prev;
prev=cur;
cur=temp;
}
return prev;
}
};
递归写法
class Solution {
public:
ListNode* reverse(ListNode* cur,ListNode* prev)
{
//递归结束条件
if(cur==NULL)return prev;
ListNode* temp=cur->next;
cur->next=prev;
return reverse(temp,cur);
}
ListNode* reverseList(ListNode* head) {
if(head==NULL)return NULL;
return reverse(head,NULL);
}
};