迭代
- 三个变量记录位置
- 写循环
时间复杂度
O(n)
C++ 代码
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return NULL;
if(!head->next) return head;
ListNode *p=head,*q=head->next,*r=head->next->next;
while(p&&q&&r){
q->next=p;
p=q;
q=r;
r=r->next;
}
q->next=p;
head->next=NULL;
return q;
}
};
算法2
递归
其实不是很好想,看了题解才懂得
时间复杂度
O(n)
空间复杂度
O(n)
C++ 代码
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return NULL;
if(!head->next) return head;
ListNode* tail = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return tail;
}
};