自己首先用迭代写出来了,然后看了官方的写了一遍,发现没有理解透,又看了一遍写了一下
class Solution {//第一遍
public:
ListNode* reverseList(ListNode* head) {
if(!head)
return head;
ListNode *dummy=new ListNode(0,head);
ListNode*l=dummy,*r=head->next,*tail=head;
while(r){
head->next=l;
l=head;
head=r;
r=r->next;
}
head->next=l;
tail->next=NULL;
delete(dummy);
return head;
}
};
*****************************************************************
class Solution {//第二遍
public:
ListNode* reverseList(ListNode* head) {
if(!head)
return head;
ListNode* cur=head->next;
ListNode* pre=head;
head->next=NULL;
while(cur){
ListNode*next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
};
**********************************************************************
class Solution {//第三遍
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur=head;
ListNode* pre=nullptr;
while(cur){
ListNode*next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
};
光放题解中这个pre初始值设置的非常巧妙,既完成了将反转后最后一个元素(即反转前头结点)的next置空,又将头结点也为空这一情况考虑到普适循环中!