-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertNodeMiddleLinkedList.java
More file actions
77 lines (74 loc) · 2.12 KB
/
InsertNodeMiddleLinkedList.java
File metadata and controls
77 lines (74 loc) · 2.12 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package Ds.Achievers;
import java.util.Scanner;
public class InsertNodeMiddleLinkedList {
static Node head;
static class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
InsertNodeMiddleLinkedList add(InsertNodeMiddleLinkedList list, int data){
Node newNode = new Node(data);
if (head == null)
head = newNode;
else {
newNode.next = head;
head = newNode;
}
return list;
}
void display(){
Node ptr = head;
while (ptr != null){
System.out.print(ptr.data+" --> ");
ptr = ptr.next;
}
}
void insertAtMiddle(int data){
if (head == null)
head = new Node(data);
else {
Node newNode = new Node(data);
Node ptr = head;
int length = 0;
while (ptr != null){
length++;
ptr = ptr.next;
}
int position = 0;
if (length % 2 == 0)
position = length / 2;
else
position = (length + 1) / 2;
ptr = head;
while (position > 1){
ptr = ptr.next;
position--;
}
newNode.next = ptr.next;
ptr.next = newNode;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
InsertNodeMiddleLinkedList list = new InsertNodeMiddleLinkedList();
System.out.println("enter elements to insert(-1 to exit)");
int element = sc.nextInt();
while (element != -1){
list.add(list, element);
element = sc.nextInt();
}
System.out.println("created linked list is: ");
list.display();
System.out.print("null");
System.out.println("\nenter element to insert in middle");
int middle = sc.nextInt();
list.insertAtMiddle(middle);
System.out.println("created linked list is: ");
list.display();
System.out.print("null");
}
}