-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list_middle_element.java
More file actions
46 lines (44 loc) · 1.22 KB
/
linked_list_middle_element.java
File metadata and controls
46 lines (44 loc) · 1.22 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
//Write a program to find the middle element of the linked list.
public class linked_list_middle_element {
static Node head;
static void printData(Node head) {
Node curr = head;
while (curr != null) {
System.out.print(curr.data + "---->");
curr = curr.next;
}
System.out.print("null");
}
static int length() {
int count = 0;
Node cur = head;
while (cur != null) {
count++;
cur = cur.next;
}
return count;
}
static void middleNumber(){
int len = length();
if ( len == 0){
System.out.println("List is Empty");
}
int middle = len / 2;
Node curr = head;
for( int i = 0; i < middle; i++){
curr = curr.next;
}
System.out.println(curr.data);
}
public static void main(String[] args) {
head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
printData(head);
System.out.println();
System.out.println("Middle Element is: ");
middleNumber();
}
}