原题:
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恰好为链表的长度。其他的就很简单了,可以AC的C++代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverse(ListNode *head){
if(!head || !head->next){
return head;
}
ListNode *first = head;
ListNode *second = head->next;
ListNode *temp = NULL;
while(second){
temp = second->next;
second->next = first;
first = second;
second = temp;
}
head->next = NULL;
return first;
}
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(m > n || m < 1 || n < 1)
return NULL;
if(m == n){
return head;
}
int length = 0;
ListNode *pHead = head;
while(pHead){
length ++;
pHead = pHead->next;
}
pHead = head;
if(length < n){
return NULL;
}
ListNode *start, *end, *middle = NULL;
length = 0;
while(pHead){
length ++;
if(length == m)
start = pHead;
if(length == m-1)
middle = pHead;
if(length == n)
end = pHead;
pHead = pHead->next;
}
pHead = end->next;
end->next = NULL;
ListNode *part = reverse(start);
if(middle)
middle->next = part;
else
head = part;
while(part && part->next){
part = part->next;
}
part->next = pHead;
return head;
}
};

551

被折叠的 条评论
为什么被折叠?



