原题

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 ≤ mn ≤ length of list.

地址

https://leetcode.com/problems/reverse-linked-list-ii/

程序范例

[code lang=”cpp”]
/**
* 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) {
ListNode* chead = head;
int data[10000] = {};
for (int i = 0; i < n; i++) { data[i] = chead->val;
chead = chead->next;
}

int mid = (m + n)>>1;
for (int left = m – 1; left <= mid – 1; left++) {
int right = (n – 1) – (left – (m – 1));
if (right <= left) {
// while up to the mid index
break;
}
int tmp = data[left];
data[left] = data[right];
data[right] = tmp;
}

chead = head;
for (int i = 0; i < n; i++) {
std::cout<<data[i]<<std::endl;
}

for (int i = 0; i < n; i++) { if (i >= m – 1) {
chead->val = data[i];
}
chead = chead->next;
}

return head;
}
};
[/code]

时间复杂度

O(n^3)


文章来源:胡旭博客 => LeetCode OJ Algorithm – reverse linked list ii (medium)

转载请注明出处,违者必究!

Share:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.