反转链表
递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
//先反转head后面的链表,最后将head接在新链表最后即可
auto tail=reverseList(head->next);
//将head从新链表尾部接上去
head->next->next=head;
head->next=NULL;
return tail;//tail是反转后的链表的新头节点
}
};
迭代
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return NULL;
auto a=head;auto b=head->next;
a->next=NULL;
while(a&&b)
{
auto c=b->next;
b->next=a;
a=b;
b=c;
}
return a;
}
};
有帮助的话可以点个赞,我会很开心的~

浙公网安备 33010602011771号