-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMidPoint_of_List.java
61 lines (59 loc) · 1.34 KB
/
MidPoint_of_List.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
package Programs2;
import java.util.Scanner;
class List<T> {
T data;
List<T> next;
List(T d) {
data = d;
}
}
public class MidPoint_of_List {
static List createLinkedList() {
Scanner s = new Scanner(System.in);
System.out.print("Enter data : ");
int data = s.nextInt();
List head = null;
List temp=null;
while (data != -1) {
List node = new List(data);
if (head == null) {
head = node;
temp=head;
} else {
temp.next=node;
temp=temp.next;
}
System.out.print("Enter next data : ");
data = s.nextInt();
}
return head;
}
static void display(List head)
{
List temp=head;
while(temp!=null){
System.out.print(temp.data+" ");
temp= temp.next;
}
}
public static int printMiddel(List<Integer> head) {
List temp=head;
List<Integer> slow=head,fast=head.next;
while(fast!=null&&fast.next!=null)
{
slow=slow.next;
fast=fast.next.next;
}
return slow.data;
}
public static void main(String[] args) {
List head = createLinkedList();
Scanner s=new Scanner(System.in);
List temp = head;
System.out.println();
System.out.print("Linked List formed is : ");
display(temp);
System.out.println();
System.out.print("Middle Element of the Linked List is : "+printMiddel(head));
}
}