-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq2p8.java
More file actions
55 lines (52 loc) · 1.25 KB
/
Copy pathq2p8.java
File metadata and controls
55 lines (52 loc) · 1.25 KB
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
public class q2p8{
public static void main(String[] args){
Node head1 = new Node(0);
head1.append(1);
head1.append(2);
head1.append(3);
head1.append(4);
head1.append(5);
head1.append(6);
head1.append(7);
head1.append(8);
head1.append(9);
head1.append(10);
head1.append(11);
head1.append(12);
head1.last.next = head1.next.next.next.next.next;
find(head1);
}
public static void find(Node head){
Node fast = head;
Node slow = head;
do{
fast = fast.next.next;
slow = slow.next;
}while(fast != slow);
slow = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
System.out.println(slow.value);
}
}
// T: O(n)
// S: O(1)
class Node{
public Node next = null;
public int value;
public Node last = null;
public Node(int value){
this.value = value;
}
public void append(int value){
Node end = new Node(value);
Node previous = this;
while(previous.next != null){
previous = previous.next;
}
previous.next = end;
last = end;
}
}