forked from kishanrajput23/Java-Projects-Collections
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddElementinlinkedList
53 lines (50 loc) · 1.46 KB
/
addElementinlinkedList
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
import java.util.Scanner;
public class insertioninSortedLL {
public static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
public static class Linkedlist2 {
Node head = null;
Node tail = null;
void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
void toAddElement(int val) { //
Node n = new Node(val);
Node temp = head;
Node prev = null;
while(temp!=null){
if(temp.data>val)break;
prev=temp;
temp=temp.next;
}
if(prev!=null){
Node cur=prev.next;
prev.next=n;
n.next=cur;
} else {
n.next=head;
head=n;
}
}
}
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
Linkedlist2 obj = new Linkedlist2();
for(int i =1;i<=5;i++){
System.out.println("enter the number ");
int n =sc.nextInt();
obj. toAddElement(n);
}
obj. display();
}
}