美文网首页
92. Reverse Linked List II

92. Reverse Linked List II

作者: juexin | 来源:发表于2017-01-05 16:24 被阅读0次

    Reverse a linked list from position m to n. Do it in-place and in one-pass.
    For example:Given1->2->3->4->5->NULL, m = 2 and n = 4,
    return1->4->3->2->5->NULL.
    Note:Given m, n satisfy the following condition:1 ≤ mn ≤ length of list.

    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            if(head==NULL||m == n)
              return head;
            
            ListNode* dummy = new ListNode(-1);
            dummy->next = head;
            ListNode* p = head;
            ListNode* q = dummy;
            for(int i=0;i<m-1;i++)
            {
                q = p;
                p = p->next;
            }
            ListNode* pre = NULL;
            ListNode* cur = p;
            
            for(int i=m;i<=n;i++)
            {
                ListNode* pNext = cur->next;
                cur->next = pre;
                pre = cur;
                cur = pNext;
            }
            q->next = pre;
            p->next = cur;
            return dummy->next;
        }
    };
    

    相关文章

      网友评论

          本文标题:92. Reverse Linked List II

          本文链接:https://www.haomeiwen.com/subject/lwuzvttx.html