-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc-141.java
47 lines (39 loc) · 1.09 KB
/
lc-141.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
//注意,这里的循环并不只有收尾循环,而是任意一个部分的循环
//经典解法,用快慢指针
/*public boolean hasCycle(ListNode head) {
if(head == null || head.next == null)return false;
ListNode fast = head,slow = fast;
while(fast != null && fast.next != null) {
if(fast.next != slow) {
slow = slow.next;
fast = fast.next.next;
}else return true;
}
return false;
}*/
//不使用额外空间,破坏链表的存储,使遍历过的结点都指向头结点
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode first = head;
while(head != null) {
if(head.next == first) return true;
else {
ListNode temp = head;
head = head.next;
temp.next = first;
}
}
return false;
}
}