LeetCode刷题-206. Reverse Linked List(反转链表)

反转一个单链表。

示例:

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

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

解法一

逆序可以考虑堆栈,先遍历整个链表,并同时把元素pushpush进堆栈,然后poppop出来构造出新的链表即反转后的链表,时间复杂度O(N)O(N),空间复杂度O(N)O(N)

/**
 * 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 == nullptr || head -> next == nullptr) {
            return head;
        }
        stack<ListNode*> nodes;
        while (head != nullptr) {
            nodes.push(head);
            head = head -> next;
        }
        head = nodes.top();
        nodes.pop();
        ListNode* temp = head;
        while (!nodes.empty()) {
            ListNode* node = nodes.top();
            nodes.pop();
            temp -> next = node;
            temp = node;
        }
        temp -> next = nullptr;
        return head;
    }
};

解法二:

解法一利用了堆栈,空间复杂度为O(N)O(N),为了进一步优化空间复杂度,进行原地反转,新定义两个辅助指针即可解决该问题。

/**
 * 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 == nullptr || head -> next == nullptr) {
            return head;
        }
        ListNode *p1 = head -> next, *p2 = nullptr;
        head -> next = nullptr;
        p2 = p1 -> next;
        p1 -> next = head;
        head = p2;
        while (head != nullptr) {
            p2 = head -> next;
            head -> next = p1;
            p1 = head;
            head = p2;
        }
        return p1;
    }
};

解法三:

解法一用了堆栈思想,任何递归问题可转化为迭代问题,但迭代问题不一定可以转化为递归解决,想了想,函数调用本就是栈的规律,可以采取递归解决该问题。

/**
 * 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, ListNode* pre = nullptr) {
        if (head == nullptr) {
            return head;
        }
        if (head -> next == nullptr) {
            head -> next = pre;
            return head;
        }
        ListNode *tmp = head -> next;
        head -> next = pre;
        return reverseList(tmp, head);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章