[LeetCode] Reverse Linked List II

Source: Internet
Author: User

[LeetCode] Reverse Linked List II

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-> NULL, m = 2 and n = 4,

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

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

This problem is slightly modified on the reverse of a single-chain table, requiring that only the chain table be reversed from the m to the n node. Take two steps:
1. Locate the m Node
2. Reverse until the nth node: If a node is not met, insert it to the front of the m node and continue to the next node.

Note the following during the operation:
1. A pointer pointing to the first m node is required.
2. If m = n, no operation is required.

Paste the code below:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *reverseBetween(ListNode *head, int m, int n) {        if (m == n)            return head;        ListNode* first = new ListNode(0);        int len = n - m;        first->next = head;        ListNode* p = first;        while (p&&m > 1){            p = p->next;            m--;        }        ListNode* q = p->next;        ListNode* tail = q;        p->next = NULL;        ListNode* r = NULL;        while (q&&len >= 0){            r = q->next;            q->next = p->next;            p->next = q;            q = r;            len--;        }        tail->next = r;        return first->next;    }};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.