您的位置:首页 > 其它

LeetCode之Reverse Linked List II

2015-03-26 09:33 267 查看
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*改变链表的顺序,采用头插法即可。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode newHead(-1);
ListNode *pre = &newHead;
pre->next = head;
for(int i = 0; i < m - 1; ++i){
pre = pre->next;
}
ListNode *cur = pre->next->next;
ListNode *tail = pre->next;
tail->next = nullptr;
for(int i = 0; i < n - m; ++i){//头插法
ListNode *tmp = cur;
cur = cur->next;
tmp->next = pre->next;
pre->next = tmp;
}
if(cur != nullptr) tail->next = cur;
return newHead.next;
}
};



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