Reverse Linked List II
2014-04-30 20:49
106 查看
Problem:
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.
分析:
链表的反转是经典的问题,Reorder List中问题中也有涉及。三个指针,一个维护头部元素的指针(head),一个维护新链表尾部的指针(tail),另外一个是将要插入到链表头部元素的指针(cur)。顺序从第二个元素开始,依次向后取每个元素,将其插入链表的头部。时间复杂度O(n)。
这个题目唯一不同点在于,需要获取到第m个节点的前驱,使链表能够接好。为了代码的简洁与一致,避免判断m=1为头节点时的麻烦,可以在头部加入哨兵(代码第7-8行),然后循环找到m节点的前驱(第9-12行),而后的反转就是经典的问题了(第13-19行)。
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.
分析:
链表的反转是经典的问题,Reorder List中问题中也有涉及。三个指针,一个维护头部元素的指针(head),一个维护新链表尾部的指针(tail),另外一个是将要插入到链表头部元素的指针(cur)。顺序从第二个元素开始,依次向后取每个元素,将其插入链表的头部。时间复杂度O(n)。
if(head == NULL) return; ListNode *tail = head; while(tail->next) { ListNode *cur = tail->next; tail->next = cur->next; cur->next = head; head = cur; }
这个题目唯一不同点在于,需要获取到第m个节点的前驱,使链表能够接好。为了代码的简洁与一致,避免判断m=1为头节点时的麻烦,可以在头部加入哨兵(代码第7-8行),然后循环找到m节点的前驱(第9-12行),而后的反转就是经典的问题了(第13-19行)。
class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { if(head == NULL || m == n || m < 1 || m > n) return head; ListNode *sentinel = new ListNode(0); sentinel->next = head; ListNode *pre = sentinel; for(int i = 1; i < m; ++i) { pre = pre->next; } ListNode *tail = pre->next; for(int i = m; i < n; ++i) { ListNode *cur = tail->next; tail->next = cur->next; cur->next = pre->next; pre->next = cur; } head = sentinel->next; delete sentinel; return head; } };
相关文章推荐
- leetcode[92]Reverse Linked List II
- Reverse Linked List II
- LeetCode: Reverse Linked List II
- Reverse Linked List II
- LeetCode | Reverse Linked List II
- Reverse Linked List II
- 【leetcode】Reverse Linked List II
- Reverse Linked List II
- 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 II
- Leetcode 92 Reverse Linked List II
- [LeetCode]Reverse Linked List II
- 92. Reverse Linked List II
- Reverse Linked List II
- 92. Reverse Linked List II
- leetcode 92 Reverse Linked List II C++
- Leetcode_reverse-linked-list-ii