【LeetCode】206. Reverse Linked List (2 solutions)

Reverse Linked List

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

解法一:非递归

/**
 * 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;
        else if(head->next->next == NULL)
        {
            ListNode* newhead = head->next;
            newhead->next = head;
            head->next = NULL;
            return newhead;
        }
        else
        {
            ListNode* pre = head;
            ListNode* cur = pre->next;
            pre->next = NULL;
            ListNode* post = cur->next;
            
            while(post != NULL)
            {
                cur->next = pre;
                pre = cur;
                cur = post;
                post = post->next;
            }
            cur->next = pre;
            return cur;
        }
    }
};

解法二:递归

每个节点都调到尾部去

/**
 * 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 = head;
        while(newhead->next != NULL)
            newhead = newhead->next;
        reverse(head);
        return newhead;
    }
    ListNode* reverse(ListNode* head)
    {
        if(head->next == NULL)
            return head;
        else
        {
            ListNode* tail = reverse(head->next);
            tail->next = head;
            tail = tail->next;
            tail->next = NULL;
            return tail;
        }
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4482958.html