思路
看了下题解,有递归和迭代两种方法,但是对于递归来说,空间复杂度都大幅增加到O(N)。所以我这里用更加好理解的迭代。
做这题先把链表画出来。再去写代码会清楚点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode*cur=head;//头
ListNode*pre=nullptr;//尾
while(cur!=NULL)
{
ListNode*tmp=cur->next;
cur->next=pre;//把头指针指向末尾
pre=cur;//把尾指针指向头
cur=tmp;//原来的头指针下移
}
return pre;//此时pre成为头指针
}
};