方法1:
非递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* pre=head;
head=head->next;
ListNode* next=head->next;
pre->next=NULL;
while(next)
{
head->next=pre;
pre=head;
head=next;
next=next->next;
}
head->next=pre;
return head;
}
};
方法2:
递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* p=head->next;
ListNode* q=reverseList(p);
p->next=head;
head->next=NULL;
return q;
}
};
本文介绍链表逆序的两种实现方式:非递归和递归方法。非递归方式通过迭代设置指针指向来完成逆序;递归方法则利用函数调用栈将链表节点依次反转。
424

被折叠的 条评论
为什么被折叠?



