[Leetcode] 92. Reverse Linked List II 解题报告
2017-04-19 09:17
399 查看
题目:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
return
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
思路:
这道题目的思路不难,需要注意的是in-place和one-pass的要求。假设需要翻转m到n之间的元素,那么我们首先定位到m位置,然后遍历并且依次翻转,直到到达n位置。最后把m位置的元素和n之后的元素连接起来即可。为了处理方便,仍然引入虚拟头结点。
代码:
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.
思路:
这道题目的思路不难,需要注意的是in-place和one-pass的要求。假设需要翻转m到n之间的元素,那么我们首先定位到m位置,然后遍历并且依次翻转,直到到达n位置。最后把m位置的元素和n之后的元素连接起来即可。为了处理方便,仍然引入虚拟头结点。
代码:
/** * 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 || n - m <= 0) { return head; } ListNode pre_head(0); pre_head.next = head; ListNode* p = &pre_head; ListNode* post; int i = 1; while(i < m && p) { // come to position m p = p->next; i++; } post = p->next; ListNode* q = post->next; while(q && i < n) { // traverse until position n ListNode* temp = q->next; q->next = p->next; p->next = q; q = temp; i++; } post->next = q; return pre_head 4000 .next; } };
相关文章推荐
- 【LeetCode】92. Reverse Linked List II 解题报告
- Leetcode 92. Reverse Linked List II 翻转链表2 解题报告
- LeetCode 92. Reverse Linked List II 解题报告
- [leetcode] 92. Reverse Linked List II 解题报告
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- [LeetCode] Reverse Linked List II 解题报告
- 【LeetCode】Reverse Linked List II 解题报告
- LeetCode解题报告—— Reverse Linked List II & Restore IP Addresses & Unique Binary Search Trees II
- leetCode 92.Reverse Linked List II (反转链表II) 解题思路和方法
- LeetCode92 Reverse Linked List II 解题报告
- [LeetCode] Reverse Linked List II 解题报告
- [LeetCode]Reverse Linked List II解题报告
- [LeetCode]Reverse Linked List II, 解题报告
- [Leetcode]@python 92. Reverse Linked List II
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
- 【LeetCode】92. Reverse Linked List II 解法及注释
- Leetcode 92. Reverse Linked List II
- 【LeetCode】92. Reverse Linked List II
- LeetCode 92. Reverse Linked List II
- LeetCode-Reverse Linked List-解题报告