LeetCode 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==NULL || head->next==NULL || (m==n))
return head;
ListNode * current=head;
ListNode * prev=NULL;
ListNode * next;
ListNode * temp;
ListNode *p;
int cnt=n-m;
while(m--){
p=prev;
prev=current;
current=current->next;
}
temp=prev;
while(cnt--){
next=current->next;
current->next=prev;
prev=current;
current=next;
}
if(p==NULL)
head=prev;
else
p->next=prev;
temp->next=current;
return head;
}
};
No comments:
Post a Comment