-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertInMiddleOfLinkedList.java
85 lines (66 loc) · 1.84 KB
/
InsertInMiddleOfLinkedList.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.*;
import java.io.*;
class Node {
int data;
Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
Node head = new Node(sc.nextInt());
Node tail = head;
for(int i=0; i<n-1; i++){
tail.next = new Node(sc.nextInt());
tail = tail.next;
}
int key = sc.nextInt();
//display(head);
Solution obj = new Solution();
obj.insertInMid(head, key);
display(head);
System.out.println();
}
}
public static void display(Node head){
Node curr = head;
while(curr != null){
System.out.print(curr.data+" ");
curr = curr.next;
}
}
}
class Solution {
public Node insertInMid(Node head, int data){
Node newNode = new Node(data);
if(head == null){
head = newNode;
return head;
}
int size = sizeOfLinkedList(head);
int insertPosition = (size % 2) == 0 ? (size/2) : (size/2)+1;
Node prev = head;
while(insertPosition > 1){
prev = prev.next;
insertPosition--;
}
newNode.next = prev.next;
prev.next = newNode;
return head;
}
public int sizeOfLinkedList(Node head){
int size = 0;
Node iterator = head;
while(iterator != null){
iterator = iterator.next;
size++;
}
return size;
}
}