判断一个单链表是否有环,如果有,找出环的起始位置

How can one determine whether a singly linked list has a cycle?

第一种方法是从单链表head开始,每遍历一个,就把那个node放在hashset里,走到下一个的时候,把该node放在hashset里查找,如果有相同的,就表示有环,如果走到单链表最后一个node,在hashset里都没有重复的node,就表示没有环。 这种方法需要O(n)的空间和时间。


第二种方法是设置两个指针指向单链表的head, 然后开始遍历,第一个指针走一步,第二个指针走两步,如果没有环,它们会直接走到底,如果有环,这两个指针一定会相遇。


现在找出环的起始位置:

/* (Step 1) Find the meeting point. This algorithm moves two pointers at * different speeds: one moves forward by 1 node, the other by 2. They * must meet (why? Think about two cars driving on a track—the faster car * will always pass the slower one!). If the loop starts k nodes after the * start of the list, they will meet at k nodes from the start of the * loop. */ n1 = n2 = head; while (TRUE) { n1 = n1->next; n2 = n2->next->next; if (n1 == n2) { break; } } // Find the start of the loop. n1 = head; while (n1->next != n2->next) { n1 = n1->next; n2 = n2->next; } Now n2 points to the start of the loop.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值