Two pointers (1) -- Linked List Cycle II, Rotate List
2017-01-22 16:04
381 查看
Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
此题之前已有过介绍。 可以看这篇的解释,很详细:点击打开链接
Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
1. 先找出list的长度,然后找到断开处的指针。
2. 使用快慢指针的话并不能减少指针移动的操作,所以不用了
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
此题之前已有过介绍。 可以看这篇的解释,很详细:点击打开链接
ListNode *detectCycle(ListNode *head) { if (head == NULL) return NULL; ListNode* ptr = head; ListNode* fastPtr = ptr; do { if (fastPtr == NULL || fastPtr->next == NULL) return NULL; ptr = ptr -> next; fastPtr = fastPtr -> next -> next; } while (ptr != fastPtr); ptr = head; while (ptr != fastPtr){ ptr = ptr -> next; fastPtr = fastPtr -> next; } return ptr; }
Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
1. 先找出list的长度,然后找到断开处的指针。
2. 使用快慢指针的话并不能减少指针移动的操作,所以不用了
ListNode* rotateRight(ListNode* head, int k) { if (head == NULL) return NULL; int len = 1; ListNode* ptr = head; while (ptr -> next != NULL){ ptr = ptr -> next; len++; } ListNode* tail = ptr; k = k % len; if (k == 0) return head; ptr = head; for (int i = 1; i < len - k; i++){ ptr = ptr -> next; } ListNode* newH = ptr -> next; ptr -> next = NULL; tail -> next = head; return newH; }
相关文章推荐
- Linked List Cycle II
- Leetcode: Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- linked-list-cycle-ii
- Leetcode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- 【LeetCode题解】142_环形链表2(Linked-List-Cycle-II)
- [leetcode][list][two pointers] Linked List Cycle II
- 【leetcode】Linked List Cycle II
- Linked List Cycle I,II, Partition List
- Linked List Cycle II
- 【leetcode】Linked List Cycle && Linked List Cycle II
- leetcode:Linked List Cycle II
- 【Leetcode】【Medium】Linked List Cycle II
- Linked List Cycle II
- LeetCode: linked list cycle I and II
- [leetcode] Linked List Cycle II
- 142. Linked List Cycle II
- Linked List Cycle II