Day006:Linked List Cycle II
2017-03-15 15:35
225 查看
Problem:
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?
Difficulty:
Solution:
Read all the node of list,k mean the k node of a list,then from the head pointer to this node,count the number of next time.if the number is equal to k,the node is not the node we need,if the number is not equal to k,we find the node,and the list is a cycle.
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?
Difficulty:
Solution:
Read all the node of list,k mean the k node of a list,then from the head pointer to this node,count the number of next time.if the number is equal to k,the node is not the node we need,if the number is not equal to k,we find the node,and the list is a cycle.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ using namespace std; class Solution { public: ListNode *detectCycle(ListNode *head) { if (head == nullptr || head->next == nullptr){ return NULL; } if(head->next == head){ return head; } int i = 0; int j = 0; int k = 0; ListNode* node=head; ListNode* node1=nullptr; while(true){ i = i + 1; j = 0; node1 = head; while(true){ j = j+ 1; if (node1 == node){ k = j; break; } node1 = node1->next; } if(i != k){ return node; } node = node->next; if (node == nullptr){ return NULL; } } } };
相关文章推荐
- Linked List Cycle II
- Linked List Cycle II
- 【LeetCode】Linked List Cycle II
- JAVA-Linked List Cycle I&&Linked List Cycle II
- leetcode day5 -- Reorder List && Linked List Cycle II
- Linked List Cycle II
- LEETCODE: Linked List Cycle II
- [LeetCode#142]Linked List Cycle II
- LinkedList-142-Linked List Cycle II
- LeetCode — Linked List Cycle II 解题报告
- [LeetCode][JavaScript]Linked List Cycle II
- [leetcode]142 Linked List Cycle II
- Linked List Cycle II
- 【leetcode】 Linked_List_Cycle_II
- 【LeetCode】Linked List Cycle II
- [LeetCode]Linked List Cycle II解法学习
- 【leetcode刷题笔记】Linked List Cycle II
- Linked List Cycle I,II, Partition List
- Linked List Cycle II
- leetcode:Linked List Cycle II