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

leetcode 日经贴,Cpp code -Reverse Linked List II

2015-05-05 18:30 676 查看
Reverse Linked List II

/**
* 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) {
if (!head || !head->next || m >= n) {
return head;
}
ListNode *cur = head, *pre = NULL;
int k = n - m;
while (--m) {
pre = cur;
cur = cur->next;
}
//reverse
ListNode *tail = cur;
ListNode *h = cur;
cur = cur->next;
while (cur && k--) {
ListNode *next = cur->next;
cur->next = h;
h = cur;
cur = next;
}
if (pre) {
pre->next = h;
} else {
head = h;
}
//after reverse
tail->next = cur;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: