1. 程式人生 > >[LeetCode-141] Linked List Cycle(判斷連結串列是否有環)

[LeetCode-141] Linked List Cycle(判斷連結串列是否有環)

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

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

【分析】

由於每一個父親只有可能有一個孩子,故這裡的環實際上是指list中某一個節點的孩子同時也是它自己或者他的祖先。 這個問題需要注意幾種情況:

1. 空連結串列不成環

2. 一個節點自環

3. 一條連結串列完整成環

不能開額外的空間,即空間複雜度是o(1)。該問題是經典面試問題,其標準解法是用兩個指標,一快一慢,如果在快的指標能夠追上慢的指標,則有環,否則無環。

程式碼如下:

/**
 * Definition for singly-linked list.
 **/
 struct ListNode {
    int val;
    struct ListNode *next;
 };
 
 bool hasCycle(struct ListNode *head) {
	 if(!head)
		 return false;
	 struct ListNode *fast = head;
	 struct ListNode *slow = head;
 
	 while(fast!=NULL&&fast->next!=NULL) {
		 
		 fast = fast->next->next;
		 slow = slow->next;
		 if(fast==slow)
			 return true;
	 }
	 
	 return false;
 }

改進版的程式碼

/*Improved version of the program*/
bool hasCycle(struct ListNode *head) {
	if(!head)
		return false;
	struct ListNode *fast = head;
	struct ListNode *slow = head;

	do {
		if(!fast||!slow) 
			return false;/*If LinkNode exist NULL node,then return false*/
		fast = fast->next;
		slow = slow->next;
		if(fast) 
			fast = fast->next;
		else 
			return false;/*If LinkNode exist NULL node,then return false*/
	}while(fast!=slow);

	return true;
 }