forked from seeditsolution/javaprogram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddle_linkedlist
74 lines (56 loc) · 1.38 KB
/
middle_linkedlist
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
public class LinkedList{
private Node head;
private static class Node {
private int value;
private Node next;
Node(int value) {
this.value = value;
}
}
public void addToTheLast(Node node) {
if (head == null) {
head = node;
} else {
Node temp = head;
while (temp.next != null)
temp = temp.next;
temp.next = node;
}
}
public void printList() {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}
// This function will find middle element in linkedlist
public Node findMiddleNode(Node head)
{
Node slowPointer, fastPointer;
slowPointer = fastPointer = head;
while(fastPointer !=null) {
fastPointer = fastPointer.next;
if(fastPointer != null && fastPointer.next != null) {
slowPointer = slowPointer.next;
fastPointer = fastPointer.next;
}
}
return slowPointer;
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
// Creating a linked list
Node head=new Node(5);
list.addToTheLast(head);
list.addToTheLast(new Node(6));
list.addToTheLast(new Node(7));
list.addToTheLast(new Node(1));
list.addToTheLast(new Node(2));
list.printList();
// finding middle element
Node middle= list.findMiddleNode(head);
System.out.println("Middle node will be: "+ middle.value);
}
}