您的位置:首页 > 编程语言 > C语言/C++

LeetCode(92): Reverse Linked List II (C++)

2015-12-03 15:14 543 查看

一、题目

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.

二、分析

    要求只能 one-pass,且 Do it in-place,可考虑在遍历时将 m ~ n 的节点插入在 (m - 1) 节点的后面。如下图所示,对于 [1, 2, 3, 4, 5, 6] 的链表,当 m = 3, n = 5 时,反转的过程如下:



三、代码

/**
* 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 dummy(-1);
dummy.next = head;
ListNode* headLocal = &dummy;

for(int i = 0; i < m - 1; ++i){
headLocal = headLocal->next;
}

ListNode* tailLocal = headLocal->next;
ListNode* cur = tailLocal->next;

for(int i = 0; i < n - m; ++i){
tailLocal->next = cur->next;
cur->next = headLocal->next;
headLocal->next = cur;
cur = tailLocal->next;
}

return dummy.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息