05
08/2015
[LeetCode] Reverse Linked List II
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个节点正序拷贝即可。对于中间n-m+1个节点,逆序拷贝。对于剩下的节点直接连上。
/**
* 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(m>=n || m<=0){
return head;
}
ListNode* myHead = new ListNode(0);
ListNode* tail = myHead;
ListNode* p = head;
int c = 0;
while(c < m - 1 && p!=NULL){ //m-1个正序
tail->next = p;
tail = tail->next;
p = p->next;
c++;
}
ListNode* q = tail;
if(p!=NULL){
tail = p;
}
while(c < n && p!=NULL){ //n-m+1个逆序
ListNode* k = p->next;
p->next = q->next;
q->next = p;
p = k;
c++;
}
tail->next = p; //剩下的直接连接
p = myHead->next;
delete myHead;
return p;
}
};
0 条评论