forked from joharbatta/DataStructure-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddlell.java
More file actions
59 lines (51 loc) · 1.3 KB
/
Copy pathmiddlell.java
File metadata and controls
59 lines (51 loc) · 1.3 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
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.*;
public class middlell {
class Node {
int data;
Node next;
Node(int value) {
data = value;
next = null;
}
}
public static Node head = null;
public static Node last;
public void add(int value) {
Node newNode = new Node(value);
if (head == null) {
head = new Node(value);
return;
}
last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
return;
}
public static void printMiddleElement(Node head)
{
if(head==null || head.next==null)
{
System.out.println("middle element does not exist");
return;
}
Node sptr=head;
Node fptr=head;
while(fptr!=null && fptr.next!=null)
{
sptr=sptr.next;
fptr=fptr.next.next;
}
System.out.println("Middle Element is "+sptr.data);
}
public static void main(String[] arg) {
middlell obj = new middlell();
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 0; i < n; i++) {
obj.add(in.nextInt());
}
printMiddleElement(obj.head);
}
}