您的位置:首页 > 其它

leetcode--Reverse Linked List II

2013-08-18 16:13 495 查看
1.题目描述

[code]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.

[/code]



2.解法分析


解法就是头插法的变形,稍微改动一下,确定一下边界条件就好了。

[code]/**


* 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;




}


};

[/code]

 

这个题目很简单,但是我在上面竟然磨叽了一个小时,伤不起,究其原因,主要是两个while循环的判断条件打错了,写的条件和我脑海中想象的不一样,是这样的:

我本意是while(count<m&&cur)却写成了while(count<m&&!cur),好吧,我决定以后写这种判断条件尽量写成cur!=NULL,免得出这种哭笑不得的错误。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: