反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

 


 

 

//章节 - 链表    
//三、经典问题
//1.反转链表
/*
算法思想:
    递归方法,
*/
//算法实现:
/**
 * 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 *newhead = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return newhead;
    }
};
*/
/*
算法思想:
    迭代方法,
*/
//算法实现:
class Solution {
public:
    ListNode* reverseList(ListNode *head) {
        ListNode *newhead = NULL;
        ListNode *now;
        while (head != NULL) {
            now = head;         //取头
            head = head->next;   //更新原链头
            now->next = newhead; //插入新链
            newhead = now;      //更新新链头
        }
        return newhead;
    }
};