您的位置:首页 > 其它

[Leetcode]Reverse Linked List II

2013-07-04 20:13 459 查看
/**
* 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(head == NULL || head->next == NULL) return head;
ListNode dummy(0);
dummy.next = head;
head = &dummy;
ListNode *p1 = head, *p2 = head->next;
ListNode *pre;
for(int i = 0; i < m; ++i)
{
pre = p1;
p1 = p1->next;
p2 = p2->next;
}
for(int i = m; i < n; ++i)
{
ListNode *next = p2->next;
p2->next = p1;
p1 = p2;
p2 = next;
}
pre->next->next = p2;
pre->next = p1;
return dummy.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: