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.
将指定区间内的链表逆置,
原本写的版本太丑陋了,贴一个根据别人思路写出来的简洁版本。
代码语言:javascript复制/**
* 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) {
ListNode* res=new ListNode(0);
res->next=head;
ListNode* pre=res;
for(int i=0;i<m-1;i ) pre=pre->next;
ListNode* p=pre->next;
ListNode* temp;
for(int i=0;i<n-m;i )
{
temp=p->next;
p->next=temp->next;
temp->next=pre->next;
pre->next=temp;
}
return res->next;
}
};