leetcode92. Reverse Linked List II

来源:互联网 发布:mac优酷缓存视频路径 编辑:程序博客网 时间:2024/06/14 21:14

medium程度

题目:

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

把原地反转整个链表一般化,原地反转链表的第m到n个节点

我的解法是通过栈来存储节点求解,时间空间复杂度都是O(N)

AC解:

class Solution {public:    ListNode* reverseBetween(ListNode* head, int m, int n)     {        if (m == n)            return head;        stack<ListNode*> s;        //prev end 分别表示区段的前后一个节点        ListNode *p = head,*prev = nullptr,*end = nullptr;        int i = 1;        while (i++ < m)        {               prev = p;            p = p->next;        }                i = 1;        do        {            s.push(p);            p = p->next;        }while(i++ <= n - m);                end = p;                p = s.top();        s.pop();        if (m == 1)            head = p;        else            prev->next = p;        while(!s.empty())        {            ListNode* temp = s.top();            s.pop();            p->next = temp;            p = p->next;        }                p->next = end;        return head;    }

这样比较繁琐,有一种时间复杂度O(N),空间复杂度O(1)的解法,一次一次的改节点来实现,比较简单

AC解:

class Solution {public:    ListNode* reverseBetween(ListNode* head, int m, int n)     {        ListNode dummy(-1);        dummy.next = head;        ListNode* prev = &dummy;        for (int i = 0; i < m - 1; i++)            prev = prev->next;        //prev在m所在节点        ListNode* const head2 = prev;        prev = head2->next;//head2在prev之前        ListNode* cur = prev->next;//cur为当前要改的        for (int i = m; i < n; i++)        {//每次要改三个节点,然后cur像后推进            prev->next = cur->next;            cur->next = head2->next;            head2->next = cur;            cur = prev->next;        }                return dummy.next;    }};



0 0