142. Linked List Cycle II

题目链接: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 };

转载于:https://www.cnblogs.com/ming-1012/p/9946329.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值