[Leetcode 92, medium] Reverse Linked-list II

来源:互联网 发布:东北师大附中网络教育 编辑:程序博客网 时间:2024/04/29 18:10

Problem:

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.

Analysis:


Solution:

C++:

ListNode *reverseBetween(ListNode *head, int m, int n) {        ListNode* start_back = head;        ListNode* start_front = head;        if(m > 1) {            start_front = start_back->next;            for(int start = 2; start < m; ++start) {                start_back = start_front;                start_front = start_back->next;            }        }                        ListNode* end_back = start_front;        ListNode* end_front = end_back->next;        for(int end = m + 1; end <= n; ++end) {            ListNode* temp_next = end_front->next;            end_front->next = end_back;            end_back = end_front;            end_front = temp_next;        }                if(m == 1)            head = end_back;        else            start_back->next = end_back;        start_front->next = end_front;                return head;    }


Java:


Python:

0 0
原创粉丝点击