《进军硅谷》类似题目:环的长度
题目:给出一个单向链表头指针,如果有环,判断环的长度,否则返回0;
思路:
1 判断链表是否有环。 使用快慢指针,如果快指针已经到尾部,而且他们没有相遇,则无环;如果他们相遇,则有环
2 上图为例:
慢指针:9->8->7->1;
快指针:7->2->4->1;
判断是否有环:在快指针到尾前,快慢指针能否相等;如果相等,则有环;否则无环
计算环的长度:快慢指针相等时,从慢指针开始,遍历一遍环,计算环的长度;
C#代码如下:
判断是否有环版本:
<span style="white-space:pre"> </span>/// <summary>
/// 判断LinkedList中是否有闭环。
/// </summary>
/// <param name="head"></param>
/// <returns></returns>
public static bool HasCircle(LinkedListNode<int> head)
{
LinkedListNode<int> slow = head;
if (slow == null || slow.Next == null)
return false;
LinkedListNode<int> fast = slow.Next.Next;
//使用快慢指针,如果快指针走到尾前,两根指针遇到,就有闭环
while (fast != null && fast.Next != null)
{
if (slow == fast) return true;
slow = slow.Next;
fast = fast.Next.Next;
}
return false;
}
C#计算环的长度:
<span style="white-space:pre"> </span>/// <summary>
/// 判断LinkedList中是否有闭环。
/// </summary>
/// <param name="head"></param>
/// <returns></returns>
public static int GetCircleLength(LinkedListNode<int> head)
{
LinkedListNode<int> slow = head;
if (slow == null || slow.Next == null)
return 0;
LinkedListNode<int> fast = slow.Next.Next;
//使用快慢指针,如果快指针走到尾前,两根指针遇到,就有闭环
while (fast != null && fast.Next != null)
{
if (slow == fast) return GetLength(slow);
slow = slow.Next;
fast = fast.Next.Next;
}
return 0;
}
private static int GetLength(LinkedListNode<int> node)
{
int length = 1;
LinkedListNode<int> curr = node;
while (curr.Next != node)
{
//转一圈,并计算长度
length++;
curr = curr.Next;
}
return length;
}
答案:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public bool HasCycle(ListNode head) {
ListNode slow = head;
if (slow == null || slow.next == null)
return false;
ListNode fast = slow.next.next;
//使用快慢指针,如果快指针走到尾前,两根指针遇到,就有闭环
while (fast != null && fast.next != null)
{
if (slow == fast) return true;
slow = slow.next;
fast = fast.next.next;
}
return false;
}
}