Skip to content

Commit ae9d99e

Browse files
authored
Create addElementinlinkedList
1 parent 75aade1 commit ae9d99e

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

addElementinlinkedList

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
import java.util.Scanner;
3+
4+
public class insertioninSortedLL {
5+
public static class Node {
6+
int data;
7+
Node next;
8+
Node(int data) {
9+
this.data = data;
10+
}
11+
}
12+
public static class Linkedlist2 {
13+
Node head = null;
14+
Node tail = null;
15+
16+
void display() {
17+
Node temp = head;
18+
while (temp != null) {
19+
System.out.print(temp.data + " ");
20+
temp = temp.next;
21+
}
22+
System.out.println();
23+
}
24+
void toAddElement(int val) { //
25+
Node n = new Node(val);
26+
Node temp = head;
27+
Node prev = null;
28+
while(temp!=null){
29+
if(temp.data>val)break;
30+
prev=temp;
31+
temp=temp.next;
32+
}
33+
if(prev!=null){
34+
Node cur=prev.next;
35+
prev.next=n;
36+
n.next=cur;
37+
} else {
38+
n.next=head;
39+
head=n;
40+
}
41+
}
42+
}
43+
public static void main(String[] args) {
44+
Scanner sc =new Scanner(System.in);
45+
Linkedlist2 obj = new Linkedlist2();
46+
for(int i =1;i<=5;i++){
47+
System.out.println("enter the number ");
48+
int n =sc.nextInt();
49+
obj. toAddElement(n);
50+
}
51+
obj. display();
52+
}
53+
}

0 commit comments

Comments
 (0)