Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
/*思路来源:
点击打开链接 */
/*迭代*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *new_head = NULL, *old_head = head;
while(old_head){
ListNode* temp = old_head->next;
old_head->next = new_head;
new_head = old_head;
old_head = temp;
}
return new_head;
}
};
/*递归*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
ListNode *p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};