Reverse Linked List
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
1、迭代法,超时
ListNode* reverseList(ListNode* head) {
if(!head || !head->next)return head;
ListNode dummy(-1);
ListNode* prev = &dummy;
prev->next = head;
ListNode* cur = head->next;
while(cur->next)
{
ListNode* tmp = cur;
cur->next = tmp->next;
tmp->next = dummy.next;
dummy.next = tmp;
}
return dummy.next;
}
2、递归(https://www.cnblogs.com/grandyang/p/4478820.html)
ListNode* reverseList(ListNode* head) {
if(!head || !head->next)return head;
ListNode* p = head;
head = reverseList(head->next);
p->next->next = p;
p->next = nullptr;
return head;
}