Linked List Cycle(LeetCode)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014485485/article/details/81945816

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

给你一个链表,让你在原地判断这个链表有没有环。

思路:

使用快慢指针法。遍历,如果没有环,快指针最终指向NULL,也就是结尾,如果有环,慢指针最终会追上快指针。

struct ListNode {
    int val;
	ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
	bool hasCycle(ListNode *head) {
		if (head == NULL || head->next == NULL) {
			return false;
		}
		ListNode *fast = head;
		ListNode *slow = head;

		while (fast->next!=NULL && fast->next->next!=NULL)
		{
			fast = fast->next->next;//跳两个
			slow = slow->next;//跳一个
			if (slow==fast)
			{
				return true;
			}
		}
		return false;
	}
};

猜你喜欢

转载自blog.csdn.net/u014485485/article/details/81945816
今日推荐