141. Linked List Cycle【easy】

2023-03-15,,

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;
}
};

经典的快慢指针思想

141. Linked List Cycle【easy】的相关教程结束。

《141. Linked List Cycle【easy】.doc》

下载本文的Word格式文档,以方便收藏与打印。