1.题目描述
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.
2.解法分析
解法就是头插法的变形,稍微改动一下,确定一下边界条件就好了。
/**
* 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) {// Start typing your C/C++ solution below
// DO NOT write int main() function
if(m>=n)return head;if(!head)return NULL;int count=1;
ListNode * cur=head;ListNode * start=NULL;ListNode * headPrev=NULL;while(count<m&&cur)
{headPrev=cur;cur=cur->next;count++;}start=cur;while(count<n&&cur->next)
{ListNode *temp = cur->next;cur->next=temp->next;temp->next=start;start=temp;if(headPrev)headPrev->next=start;
count++;}if(headPrev)return head;else return start;}};这个题目很简单,但是我在上面竟然磨叽了一个小时,伤不起,究其原因,主要是两个while循环的判断条件打错了,写的条件和我脑海中想象的不一样,是这样的:
我本意是while(count<m&&cur)却写成了while(count<m&&!cur),好吧,我决定以后写这种判断条件尽量写成cur!=NULL,免得出这种哭笑不得的错误。