1. 程式人生 > >Leetcode 141 Linked List Cycle(連結串列)

Leetcode 141 Linked List Cycle(連結串列)

解題思路:建立兩個指標,從起始位置開始,一個走一步,一個走兩步,如果存在環,兩個指標會有相等的時候。

/**
 * 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) {
			ListNode* one = head;
			ListNode* two = head;

			while (two != NULL) {
				one = one->next;
				two = two->next;

				if (two == NULL) return false;
				two = two->next;

				if (one == two) return true;
			}
			return false;
		}
};