Create 141. Linked List Cycle.md

This commit is contained in:
唐树森 2018-09-19 20:38:58 +08:00 committed by GitHub
parent 7427f21362
commit 29948916be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

29
141. Linked List Cycle.md Normal file
View File

@ -0,0 +1,29 @@
# [141. Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/description/)
# 思路
判断一个链表是否是环。
设置两个指针p1和p2用步长分别为1和2从前往后遍历若链表是环则p1和p2总会相遇。
时间复杂度O(n)空间复杂度O(1)
# C++
```
/**
* 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 *p1 = head, *p2 = head -> next;
while(p1 && p2 && p2 -> next){
if(p1 == p2) return true;
p1 = p1 -> next;
p2 = p2 -> next -> next;
}
return false;
}
};
```