LeetCode--Reverse Linked List II
2017-11-08 18:22
253 查看
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.
思路:头插法。这是一个翻转链表题目的扩展,在头插法的基础上考虑在一个区间内反转。那么,首先要找到prev指针,然后确定3个指针head2,prev,cur的位置,头插法把cur指针内容插到head2后面,然后更新cur指针。
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.
思路:头插法。这是一个翻转链表题目的扩展,在头插法的基础上考虑在一个区间内反转。那么,首先要找到prev指针,然后确定3个指针head2,prev,cur的位置,头插法把cur指针内容插到head2后面,然后更新cur指针。
/** * 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) { ListNode dummy(0); dummy.next=head; ListNode *prev=&dummy; for(int i=0;i<m-1;i++){ prev=prev->next; } ListNode *head2=prev; prev=head2->next; ListNode *cur=prev->next; for(int i=m;i<n;i++){ prev->next=cur->next; cur->next=head2->next; head2->next=cur; cur=prev->next; } return dummy.next; } };
相关文章推荐
- LeetCode: Reverse Linked List II
- Leetcode#92 Reverse Linked List II
- LeetCode Reverse Linked List II
- Leetcode_reverse-linked-list-ii
- leetcode题解-92. Reverse Linked List II
- [Leetcode] Reverse Linked List II (Java)
- LeetCode 92. Reverse Linked List II
- LeetCode Reverse Linked List II
- (Leetcode)92. Reverse Linked List II ——反转单链表
- LeetCode 92. Reverse Linked List II
- LEETCODE: Reverse Linked List II
- LeetCode Reverse Linked List II
- C实现 LeetCode->Reverse Linked List II (双指针大法)(单链表反转)
- 92、Reverse Linked List II [Leetcode]
- leetCode 92.Reverse Linked List II (反转链表II) 解题思路和方法
- LeetCode Reverse Linked List II
- [leetcode] 92.Reverse Linked List II
- 【LeetCode】Reverse Linked List II
- leetcode - Reverse Linked List II
- [Leetcode]Reverse Linked List II