【Leetcode】141. 环形链表

题目描述:

给定一个链表,判断链表中是否有环。

进阶:
你能否不使用额外空间解决此题?

解题思路:

快慢指针。

AC代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
bool hasCycle(ListNode *head)
{
	if (head == nullptr) return false;
	auto fast = head;
	auto slow = head;
	while (fast->next != nullptr and fast->next->next != nullptr)
	{
		slow = slow->next;
		fast = fast->next->next;
		if (slow == fast) return true;
	}
	return false;
}
};

猜你喜欢

转载自blog.csdn.net/wez031113/article/details/84105159