linked-list-cycle-ii
2017-07-03 16:11
295 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?
剑指offer里也有同样的题,分为三步找到环形链表的入口结点,这里就只记录这次自己写的代码,具体的思路分析见链表中环的入口结点
代码:
Follow up:
Can you solve it without using extra space?
剑指offer里也有同样的题,分为三步找到环形链表的入口结点,这里就只记录这次自己写的代码,具体的思路分析见链表中环的入口结点
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode *meetingnode = meetingcycle(head); if(meetingnode==NULL) return NULL; //计算环内节点个数 int count = 1; ListNode *cur = meetingnode; while(cur!=NULL){ cur = cur->next; if(cur==meetingnode) break; count++;//这里要注意break和count++的顺序问题 } //寻找入口点 ListNode *slow = head; ListNode *fast = head; for(int i = 0;i < count;++i){ fast = fast->next; } while(slow!=fast){ slow = slow->next; fast = fast->next; } return slow; } //找到一个环内节点 ListNode *meetingcycle(ListNode *head){ if(head==NULL || head->next==NULL) return NULL; ListNode *slow = head; ListNode *fast = head->next; while(slow!=NULL && fast!=NULL){ if(slow==fast) return slow; slow = slow->next; fast = fast->next; if(fast!=NULL) fast = fast->next; } return NULL; } };
相关文章推荐
- LeetCode题解:Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode - Linked List Cycle I &II
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- 链表-leetcode 142 Linked List Cycle II
- LeetCode :: Linked List Cycle I and II
- LeetCode:Linked List Cycle II
- Linked List Cycle I & II
- leetcode-Linked List Cycle II
- linked-list-cycle-ii (链表判环 并返回交点)
- Linked List Cycle II(2014.2.7)
- [LeetCode]93. Linked List Cycle II查找链表中环的起始节点
- leetcode 【 Linked List Cycle II 】 python 实现
- linked-list-cycle-ii(有环链表的第一个公共节点)
- Linked List Cycle II
- [LeetCode] Linked List Cycle II, Solution
- <LeetCode OJ> 141 / 142 Linked List Cycle(I / II)
- 142. Linked List Cycle II
- Linked List Cycle II