forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 2
/
FindNthNode.java
77 lines (58 loc) · 1.8 KB
/
FindNthNode.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package linkedlist;
public class FindNthNode {
public static LinkedList.Node findNthNode(LinkedList linkedList, int n) {
LinkedList.Node fast = linkedList.head();
LinkedList.Node slow = linkedList.head();
int length = 1;
while (fast.next() != null) {
fast = fast.next();
length++;
if(length > n) {
slow = slow.next();
}
}
return slow;
}
private static class LinkedList {
private LinkedList.Node head;
private LinkedList.Node tail;
public LinkedList() {
head = new LinkedList.Node("head");
tail = head;
}
public void add(LinkedList.Node node) {
tail.setNext(node);
tail = node;
}
public LinkedList.Node head() {
return head;
}
public static class Node {
private LinkedList.Node next;
private String data;
public Node(String data) {
this.data = data;
}
public LinkedList.Node next() {
return next;
}
public void setNext(LinkedList.Node next) {
this.next = next;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
}
public static void main(String [] args) {
LinkedList linkedList = new LinkedList();
linkedList.add( new LinkedList.Node("1"));
linkedList.add( new LinkedList.Node("2"));
linkedList.add( new LinkedList.Node("3"));
linkedList.add( new LinkedList.Node("4"));
System.out.println(findNthNode(linkedList, 2).data());
}
}