141. Linked List Cycle【easy】

141. Linked List Cycle【easy】

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

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

解法一:

 /**
* 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 || head->next == NULL) {
return false;
} ListNode * slow = head;
ListNode * fast = head; while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next; if (fast == slow) {
return true;
}
} return false;
}
};

经典的快慢指针思想

上一篇:【DG】利用闪回数据库(flashback)修复Failover后的DG环境


下一篇:Swift3.0语言教程字符串大小写转化