您的位置:首页 > 其它

Reverse Linked List

2015-06-11 10:59 148 查看
思路:

方法一:迭代。

创建第二个链表,第一个链表从头掉下来的节点从头插到第二个链表中。

时间复杂度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 *second = new ListNode(-1);
        ListNode *head_tmp = head;
        while(head != nullptr) {
            ListNode *node = new ListNode(head->val);
            node->next = second->next;
            second->next = node;
            head = head->next;
            delete(head_tmp);
            head_tmp = head;
        }
        head = second->next;
        return head;
    }
};


方法二:迭代。

直接在原链表上onepass。

时间复杂度O(N),空间复杂度O(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 == nullptr || head->next == nullptr) return head;
        else {
            ListNode *pre = head;
            ListNode *cur = pre->next;
            pre->next = nullptr;
            ListNode *post = cur->next;
            while(post != nullptr) {
                cur->next = pre;
                pre = cur;
                cur = post;
                post = post->next;
            }
            cur->next = pre;
            return cur;
        }
    }
};


方法三:递归。

从头结点开始不断向下递归,到达尾节点后反转,然后回到上一层,继续。如果节点个数N过大,递归层次会很深。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
private:
    ListNode *reverse(ListNode *head) {
        if(head->next == nullptr) {
            return head;
        }else {
            ListNode *tail = reverse(head->next);
            tail->next = head;
            tail = tail->next;
            tail->next = nullptr;
            return tail;
        }
    }
public:
    ListNode* reverseList(ListNode* head) {
        if(head == nullptr || head->next == nullptr) {
            return head;
        }
        ListNode *newhead = head;
        while(newhead->next != nullptr) {
            newhead = newhead->next;
        }
        reverse(head);
        return newhead;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: