forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindMiddleNode.java
85 lines (64 loc) · 1.88 KB
/
FindMiddleNode.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
78
79
80
81
82
83
84
85
package linkedlist;
public class FindMiddleNode {
/*
* Find middle node of linked list in Java in one pass
* */
public static LinkedList.Node findMiddleNode(LinkedList linkedList) {
LinkedList.Node current = linkedList.head();
LinkedList.Node middle = linkedList.head();
int length = 0;
while (current.next() != null) {
length++;
if(length%2 == 0) {
middle = middle.next();
}
current = current.next();
}
if(length%2 == 1) {
middle = middle.next();
}
return middle;
}
private static class LinkedList {
private Node head;
private Node tail;
public LinkedList() {
head = new Node("head");
tail = head;
}
public void add(Node node) {
tail.setNext(node);
tail = node;
}
public Node head() {
return head;
}
public static class Node {
private Node next;
private String data;
public Node(String data) {
this.data = data;
}
public Node next() {
return next;
}
public void setNext(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(findMiddleNode(linkedList).data());
}
}