C++解法一:迭代法,使用前驱指针pre,当前指针cur,临时后继指针nxt;
/** * 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* pre=NULL,*cur=head; while(cur!=NULL){ ListNode* nxt=cur->next; cur->next=pre; pre=cur;cur=nxt; } return pre; } };
C++方法二:递归法,Space:O(n),Time 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) { if(head==NULL||head->next==NULL) return head; ListNode *p=reverseList(head->next); head->next->next=head; head->next=NULL; return p; } };