-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find_middle_node.java
58 lines (51 loc) · 1.3 KB
/
Find_middle_node.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
public class Find_middle_node {
private Node head;
private Node tail;
private int length;
class Node{
int value;
Node next;
Node(int value){
this.value = value;
}
}
//print list
public void printList(){
Node temp = head;
while(temp!= null){
System.out.println(temp.value);
temp = temp.next;
}
}
//add element in the list
public void append(int value){
Node n = new Node(value);
if(length == 0){
head = n;
tail = n;
}
else{
tail.next = n;
tail = n;
}
length++;
}
//Implement a method called findMiddleNode that returns the middle node of the linked list.
//If the list has an even number of nodes, the method should return the second middle node.
public Node findMiddleNode(){
Node slow = head;
Node fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
//constructor
Find_middle_node(int value){
Node newNode = new Node(value);
head = newNode;
tail = newNode;
length= 1;
}
}