您的位置:首页 > 其它

LeetCode OJ:Reverse Linked List II

2014-01-23 00:57 405 查看


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-1位置保存,将m到n位置依次next指针指向前一个元素,将第m位置元素指向n+1元素位置,m-1位置元素指向n位置元素,注意处理改变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 *p=new ListNode(0);
ListNode *q,*r,*link,*nh;
p->next=head;
nh=p;
int count=0;
while(p){
q=p->next;
if(count==m-1)link=r=p;
else if(count>=m&&count<=n){
p->next=r;
r=p;
}
if(count==n){
link->next->next=q;
link->next=p;
}
p=q;
count++;
}
return nh->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: