-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
Copy pathLinkedListCycle.java
58 lines (51 loc) · 1.37 KB
/
LinkedListCycle.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
48
49
50
51
52
53
54
55
56
57
58
package problems.easy;
import problems.utils.ListNode;
/**
* Created by sherxon on 2016-12-28.
*/
public class LinkedListCycle {
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
listNode.next = new ListNode(3);
listNode.next.next = new ListNode(2);
listNode.next.next.next = new ListNode(0);
ListNode listNode1 = insertionSortList(listNode);
}
static ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode temp = new ListNode(0);
temp.next = head;
ListNode x = head;
while (x != null) {
ListNode h = temp.next;
while (h.val < x.val && h != x) {
h = h.next;
}
ListNode te = h.next;
h.next = x;
x.next = te;
x = x.next;
}
return temp.next;
}
public boolean hasCycle(ListNode x) {
if(x==null || x.next==null)return false;
ListNode fast=x.next.next;
while(fast!=null && fast.next!=null && x.next!=null){
x=x.next;
fast=fast.next.next;
if(x==fast)return true;
}
return false;
}
}
/*
class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
* */