From 29948916beb826181c38fbbb878a6b25bc4fdd7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Wed, 19 Sep 2018 20:38:58 +0800 Subject: [PATCH] Create 141. Linked List Cycle.md --- 141. Linked List Cycle.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 141. Linked List Cycle.md diff --git a/141. Linked List Cycle.md b/141. Linked List Cycle.md new file mode 100644 index 0000000..b2fd454 --- /dev/null +++ b/141. Linked List Cycle.md @@ -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; + } +}; + ```