Linked List Cycle

来源:互联网 发布:高性能网络编程 二 编辑:程序博客网 时间:2024/06/05 18:07
/* * Solution.cpp * *  Created on: 2014年4月9日 *      Author: William */#include <iostream>using namespace std;// 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 == NULL)return false;ListNode *fast = head;ListNode *slow = NULL;// See below:while (fast != NULL && fast != slow) {if (slow == NULL)// We can use do..while.. to avoid this comparison trick.slow = head;fast = fast->next;if (fast != NULL) {fast = fast->next;slow = slow->next;}}if (fast == slow)return true;elsereturn false;}// The following function is not usable because it will damage the original linked list.// It's not a check function!!!!//bool hasCycle(ListNode *head) {//ListNode *p = head;//while (p != NULL) {//if (p->next == head)//return true;//ListNode *q = p;//// The order of next two lines is important.//p = p->next;//q->next = head;//}//return false;//}};

0 0
原创粉丝点击