您的位置:首页 > 其它

【leetcode】Reverse Linked List II

2015-01-03 12:19 323 查看

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.

思路:

首先把指针移动到第m个元素

然后计算需要交换的元素个数,n-m

每次交换时,把下一个元素交换到需要交换的初始位置



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


找到交换位置


1->
[code]2
->3->4->5->NULL

[/code]

把下一个元素交换到需要交换的初始位置

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


继续交换


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

[/code]

注意初始位置在开头时,每次交换都要更新head

/**
* 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 *p1=head;
ListNode *p1Pre=new ListNode(0);

int k=n-m;

p1Pre->next=p1;

ListNode *needDelete=p1Pre;

while(m-1>0)
{
p1Pre=p1;
p1=p1->next;
m--;
}

while(k>0)
{
ListNode* cur=p1->next;
p1->next=cur->next;

if(p1Pre->next==head)
{
head=cur;
}

cur->next=p1Pre->next;
p1Pre->next=cur;

k--;
}

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