-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSinglyLinkedList.java
More file actions
119 lines (116 loc) · 2.13 KB
/
SinglyLinkedList.java
File metadata and controls
119 lines (116 loc) · 2.13 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
public class SinglyLinkedList {
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
Node head=null;
Node tail=null;
int size;
void addNode(int data) {
Node n=new Node(data);
if(head==null) {
head=n;
tail=n;
}
else {
tail.next=n;
tail=n;
}
size++;
}
public int size() {
return size;
}
public int count() {
int c=0;
Node current=head;
while(current!=null) {
c++;
current=current.next;
}
return c;
}
void insertAtBegin(int data) {
Node n=new Node(data);
if(head==null) {
head=n;
}
else {
Node temp=head;
head=n;
n.next=temp;
}
}
void insertAtEnd(int data) {
Node n=new Node(data);
if(head==null) {
head=n;
tail=n;
}
else {
tail.next=n;
tail=n;
}
}
void insertAtPostion(int data,int idx) {
Node n=new Node(data);
Node temp=head;
if(head==null) {
head=n;
tail=n;
}
for(int i=0; i<idx-1; i++) {
temp=temp.next;
}
n.next=temp.next;
temp.next=n;
}
void insertAtmid(int data) {
int count=size%2;
Node n=new Node(data);
Node temp=head;
if(head==null) {
head=n;
tail=n;
}
for(int i=0; i<count-1; i++) {
temp=temp.next;
}
n.next=temp.next;
temp.next=n;
}
void display() {
Node cur=head;
while(cur!=null) {
System.out.print(cur.data+",");
cur=cur.next;
}
System.out.println();
}
public static void main(String[] args) {
SinglyLinkedList s1=new SinglyLinkedList();
s1.addNode(10);
s1.addNode(20);
s1.addNode(30);
s1.addNode(40);
s1.display();
System.out.println(s1.count());
System.out.println(s1.size());
System.out.println("After Inserting the Element At the Begining");
s1.insertAtBegin(100);
s1.display();
System.out.println("After Inserting the Elements At the End");
s1.insertAtEnd(200);
s1.display();
System.out.println("Insert at Any position");
s1.insertAtPostion(500,3);
s1.display();
System.out.println("After Inserting the Elements At The Middle Of the List");
s1.insertAtmid(1000);
s1.display();
}
}