标签:
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.
最麻烦的还是从头结点开始转化,考虑问题要全面。
/** * 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) { int i=1; if(head==NULL) return NULL; if(head->next==NULL) return head; if(m==n) return head; ListNode* p=head; ListNode* pM=NULL; ListNode* p1=NULL; ListNode* p2=NULL; ListNode* p3=NULL; ListNode* tail=NULL; if(m==1) { p1=head; tail=p1; p2=p1->next; p3=p2->next; if(p3==NULL) { head=p2; p2->next=p1; p1->next=NULL; return head; } } while(i<n-1) { if(i+1==m) { pM=p;//反转起点上一结点 tail=pM->next; p1=pM->next;//反转起点 p2=p1->next; p3=p2->next; } if(i>=m-1) { p2->next=p1; p1=p2; p2=p3; if(p3) p3=p3->next; } else p=p->next; i++; } if(m==1) { p2->next=p1; tail->next=p3; return p2; } if(n==2) { p2->next=p1; p1->next=p3; return p2; } pM->next=p1; tail->next=p2; return head; } };
leetCode(11):Reverse linked list II
标签:
原文地址:http://blog.csdn.net/walker19900515/article/details/46548487