I.Given a linked list, determine if it has a cycle in it.
II. Given
a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Can you solve it without using extra space?
一、两道是连着一起出的,可以说第一道题目是做第二道题目的基础,第一题也是很经典的一个题目——判断一个链表是否包含闭环。
设两个指针,一快一慢,同时步进(慢的每次步进一、快的每次步进二),那么假如快的那个最终遇到NULL,就是说明没有闭环,如果快的那一个指针,最终和慢的相遇(如果不构成环形那么一快一慢永远不会相遇),说明有闭环。
/** * 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, *slow; fast = slow = head; while(fast != NULL && fast -> next != NULL){ fast = fast -> next -> next; slow = slow -> next; if (fast == slow) return true; } return false; } };
class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode *cur = head; ListNode *fast = hasCycle(head); if (!fast) return NULL; while(cur != fast){ cur = cur -> next; fast = fast -> next; } return cur; } private: ListNode *hasCycle(ListNode *head) { if (head == NULL) return NULL; ListNode *fast, *slow; fast = slow = head; while(fast != NULL && fast -> next != NULL){ fast = fast -> next -> next; slow = slow -> next; if (fast == slow) return fast; } return NULL; } };
LeetCode :: Linked List Cycle I and II,布布扣,bubuko.com
LeetCode :: Linked List Cycle I and II
原文:http://blog.csdn.net/u013195320/article/details/22521993