leetcode--Reverse Linked List II
2013-08-18 16:13
495 查看
1.题目描述
2.解法分析
解法就是头插法的变形,稍微改动一下,确定一下边界条件就好了。
这个题目很简单,但是我在上面竟然磨叽了一个小时,伤不起,究其原因,主要是两个while循环的判断条件打错了,写的条件和我脑海中想象的不一样,是这样的:
我本意是while(count<m&&cur)却写成了while(count<m&&!cur),好吧,我决定以后写这种判断条件尽量写成cur!=NULL,免得出这种哭笑不得的错误。
[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,免得出这种哭笑不得的错误。
相关文章推荐
- LeetCode --- 92. Reverse Linked List II
- leetcode之92. Reverse Linked List II(C++读错题版本,交换一个链表中指定的两个位置上的元素)
- leetcode Reverse Linked List II
- LeetCode-92-Reverse Linked List II 链表反转 各种边界条件
- LeetCode:Reverse Linked List II 解法
- 《leetCode》:Reverse Linked List II
- LeetCode092 Reverse Linked List II
- [LeetCode] 088: Reverse Linked List II
- [LeetCode] 92. Reverse Linked List II
- [LeetCode]Reverse Linked List II
- leetcode 92 Reverse Linked List II C++
- 算法作业HW10:Leetcode92 Reverse Linked List II
- Leetcode_reverse-linked-list-ii
- [Leetcode]Reverse Linked List II
- 【Leetcode】之Reverse Linked List II
- [Leetcode] Reverse Linked List II (Java)
- [LeetCode] Reverse Linked List II @ Python [提供自创的示意图 Figure illustration]
- [Leetcode] 92. Reverse Linked List II
- LeetCode Reverse Linked List II
- leetcode 91. Reverse Linked List II