206. 反转链表
示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
1 2 3 4 5 6 7 8 9 10 11 12
| ListNode* reverseList(ListNode* head){ ListNode* temp; ListNode* cur=head; ListNode* pre =NULL; while(cur){ tmp=cur->next; cur->next=pre; pre=cur; cur=temp; } return pre; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* pre=NULL; ListNode* cur=head; ListNode* tmp; while(cur){ tmp=cur->next; cur->next=pre; pre=cur; cur=tmp; } return pre; } };
|
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: ListNode* reverse(ListNode* pre,ListNode* cur){ if(cur == NULL) return pre; ListNode* temp = cur->next; cur->next = pre; return reverse(cur,temp); } ListNode* reverseList(ListNode* head) { return reverse(NULL, head); }
};
|