您的位置:首页 > 其它

leetcode 41: Reverse Linked List II

2013-01-16 16:07 447 查看
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.

uncomplete.

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if( m>=n ) return head;

ListNode ** first = &head;
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* nxt;
while( m-- >1) cur=cur->next;

first = &( cur->next);
n = n-m+1;
while( n-- > 0 && cur!=NULL) {
nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}

(*first)->next = cur;

*first = pre;

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