题目链接:https://leetcode.com/problems/linked-list-cycle-ii/description/
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?
思路:
- 本题是141. Linked List Cycle的升级版本,不仅需要判断链表是否有环,也要确定链表的环开始结点。(在这里有141. Linked List Cycle的解答)
- 对于题目Follow up的要求,暂时没有思路,后序进行补充。
- 如果对空间复杂度没有要求,则可以利用如下思路进行解答:
- 将每个链表节点的地址存入一个集合中,当每次要添加新的链表节点地址进入集合时,先判断集合中是否有该结点的地址;
- 如果集合中没有该结点的地址则将其添加进集合;反之,则可判断此链表有环,同时该结点也是链表的环开始结点,返回该结点即可。
- 上述循环条件为当前指针所指链表结点非空。
编码如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *detectCycle(ListNode *head) { 12 if (nullptr == head) return nullptr; 13 14 set<ListNode *> include; 15 ListNode *p = head; 16 while (nullptr != p) 17 { 18 if (include.find(p) == include.end()) 19 include.insert(p); 20 else 21 { 22 set<ListNode*>::const_iterator it = include.find(p); 23 p = *it; 24 break; 25 } 26 27 p = p->next; 28 } 29 30 return p; 31 } 32 };